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.
source share