简体   繁体   中英

Retrieve current host from within an executed task

I'm using fabric to execute some remote commands on several hosts by setting:

env.hosts = [host1, host2, ...]

There are several tasks I want to perform on some of the hosts, and some I don't. is there's a way I can retrieve the current hostname the task is executing on?

Any help would be great. Thanks, Meny

Why not use different host roles?

from fabric.api import env, roles, run

env.roledefs['webservers'] = ['www1', 'www2', 'www3']

@roles('webservers')
def my_task():
    run('ls -l')

Additionally, you can get the current executing host from the env dictionary:

def my_task():
    print 'Currently executing on {0}'.format(env.host)

eclaird answer definitely helped me use a better practice when executing tasks on several hosts with different roles.

Though, while playing with it, it seems that within the task, env.host will give the name of the current hostname.
for example:

@parallel(pool_size=len(env.hosts))
def upload_to_s3(to):
    awscreds = 'some credentials...'
    cmd = '%s aws s3 sync /mnt/backup %s/%s/' % (awscreds, to, env.host)
    run(cmd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM