June 25th, 2013 by exhuma.twn
More than once I needed to create files on the staging/production box which I had no need of on the local development box (For example complex logging configuration).
This fragment contains a simple function which tries to do this in a safe manner, and also ensuring proper cleanup in case of failure.
def put_contents(value, remote_file, with_sudo=False):
"""
Uploads the contents of a variable to a remote file in a safe manner.
This will run ``mktemp`` on both the local and remote machine to reserve
unique temporary file names. Once the names are reserved, the file contents
are written as binary data into the local temp file. This local file is
then uploaded to the remote temp file and ultimately moved to the desired
destination.
:param value: The variable which contains the data to be transmitted.
:param remote_file: The target destination
:param with_sudo: If set to ``True``, the file is moved with superuser
privileges instead of the current user.
"""
move_command = with_sudo and fab.sudo or fab.run
local_temp = fab.local('mktemp', capture=True)
remote_temp = fab.run('mktemp')
with open(local_temp, 'wb') as fptr:
fptr.write(value)
with fab.settings(warn_only=True):
fab.put(local_temp, remote_temp)
execution = move_command('mv {} {}'.format(remote_temp, remote_file))
fab.local('rm {}'.format(local_temp))
if execution.failed:
abort("Unable to move the specified file!")
Posted in Coding Voodoo , Python | No Comments »