Python 如何确定fabfile中的结构角色以将特定文件发送到主机

Python 如何确定fabfile中的结构角色以将特定文件发送到主机,python,fabric,Python,Fabric,我有一个类似这样的环境: env.roledefs = { 'cisco-collectors': ['hosta', 'hostb', 'hostc'], 'brocade-collectors': ['hosta', 'hostd'] } @roles('cisco-collectors', 'brocade-collectors') def sendFiles(): for file in files[env.current_role]: put(fi

我有一个类似这样的环境:

env.roledefs = {
    'cisco-collectors': ['hosta', 'hostb', 'hostc'],
    'brocade-collectors': ['hosta', 'hostd']
}
@roles('cisco-collectors', 'brocade-collectors')    
def sendFiles():
  for file in files[env.current_role]:
    put(file)
我有一些特定的文件需要发送给具有特定角色的主机:

files = {
    'cisco-collectors': ['/path/to/filea', '/path/to/fileb'],
    'brocade-collectors': ['/path/to/filec', '/path/to/filed']
}
如何编写我的sendFiles()函数,以便在命令行上指定角色时,甚至使用
@roles()
装饰器,我都能够获得正确的文件列表

显示了一种确定主机是否属于某个角色的方法,但我需要获取当前正在执行的角色,以便知道要发送哪个文件列表

理想情况下,它将如下所示:

env.roledefs = {
    'cisco-collectors': ['hosta', 'hostb', 'hostc'],
    'brocade-collectors': ['hosta', 'hostd']
}
@roles('cisco-collectors', 'brocade-collectors')    
def sendFiles():
  for file in files[env.current_role]:
    put(file)

env.host\u string.role
在最新的
fabric
源中包含当前角色(未发布)


在我的测试中,我认为您无法可靠地在1.5中获得当前角色。参见Pavel关于这将如何改变的回答。虽然这看起来很不方便,但我认为原因是Fabric结合了主机列表,所以角色不会延续

但是,如果您不需要使用角色功能,则有一个变通方法。您可以创建一个改变主机列表的任务。不过,这只适用于一个角色

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
如果现在运行
fab role1测试
,您将看到:

[localhost] Executing task 'test'
role1
['localhost', 'example.com']
[example.com] Executing task 'test'
role1
['localhost', 'example.com']
不完全是你想要的。。。但可能会帮助你找到有效的方法