I have an environment that sort of looks like this:
env.roledefs = {
'cisco-collectors': ['hosta', 'hostb', 'hostc'],
'brocade-collectors': ['hosta', 'hostd']
}
and I have some specific files that need to be sent to hosts in specific roles:
files = {
'cisco-collectors': ['/path/to/filea', '/path/to/fileb'],
'brocade-collectors': ['/path/to/filec', '/path/to/filed']
}
How do I write my sendFiles() function so that when a role is specified on the command line, or even with the @roles()
decorator I'll be able to get the proper file list?
This question shows a way to determine if the host belongs to a role, but I need to get the role currently being executed so I know which file list to send.
Ideally it would look like this:
@roles('cisco-collectors', 'brocade-collectors')
def sendFiles():
for file in files[env.current_role]:
put(file)
env.host_string.role
contains the current role in the newest fabric
source (unreleased).
In my tests, I don't think you can reliably get the current role in 1.5. See Pavel's answer about how this will change. While this may seem inconvenient, I think the reason is that Fabric combines the list of hosts, so role doesn't carry over.
There is a workaround if you don't need to use the role functionality, though. You can create a task which alters the hosts list. This will only work for one role though!
from fabric.api import task, local, env
@task
def role1():
env.current_role = 'role1'
env.hosts.extend(['example.com'])
@task
def role2():
env.current_role = 'role2'
env.hosts.extend(['test.example.com'])
@task
def test():
print env.current_role
print env.hosts
If you now run fab role1 test
you will see:
[localhost] Executing task 'test'
role1
['localhost', 'example.com']
[example.com] Executing task 'test'
role1
['localhost', 'example.com']
Not exactly what you were after ... but may help lead you to what will work.
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.