How to target another host inside Fabric

How do you specify a different target for running a command other than the one currently set for the current Fabric command?

I have a download_backup () command that uploads a database backup file to a local host from a remote host. Since it must be executed locally, host_string is localhost. However, I need to run the command on the remote host to find out what the latest backup is. When I try to do:

def download_backup(): env.host_string = 'remotehost' env.user = 'remoteuser' backup_fn = run('ls -t /usr/local/lib/backups | head -1') 

it is still trying to run the ls on localhost. Can I change this to run on remote hosting?

+4
source share
2 answers

you can use the settings context manager to change the host on which a certain command is executed, regardless of the host settings for the attached task.

 from fabric.context_managers import settings with settings(host_string='remote_server'): run('ls -lart') 
+8
source

First of all, the reason your command is run on localhost is because env is a global variable and you redefine it locally, but this is not visible when the fabric executes the commands. You must define your host_string outside of your function.

 env.host_string = 'remotehost' env.user = 'remoteuser' def download_backup(): run('ls -t /usr/local/lib/backups | head -1') 

To change hosts at runtime, you have several options. First, you can use the roles and roledefs .

 env.roledefs = { "ex1": ["host1.example.com"], "ex2": ["host2.example.com"], } env.roles = ["ex1"] def download_backup(): run("ls -t /usr/local/lib/backups | head -1") 

By default, when you run fab download_backup you get a backup from host1.example.com , because the env.roles parameter is set to ex1 . If you want to override this parameter, you can specify the role through the command line:

 fab -R ex2 download_backup 

This will create a tag with the ex2 role and thus get it from host2.example.com .

Another option is to use the fact that env is only a global variable.

 def download_backup(): run("ls -t /usr/local/lib/backups | head -1") def download_backup_ex1(): global env env.host_string = "host1.example.com" download_backup() def download_backup_ex2(): global env env.host_string = "host2.example.com" download_backup() 

I personally prefer the first method, since it is obviously better suited to what is done in this case, but I can imagine that there are possibilities when the second approach may be a better alternative.

+2
source

Source: https://habr.com/ru/post/1439583/


All Articles