简体   繁体   English

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

[英]How to determine fabric role in fabfile to send specific files to hosts

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? 我该如何编写sendFiles()函数,以便在命令行上指定角色时,甚至使用@roles()装饰器也可以获取正确的文件列表?

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). env.host_string.role包含最新的fabric源中的当前角色(未发布)。

The commit 提交

In my tests, I don't think you can reliably get the current role in 1.5. 在我的测试中,我认为您无法可靠地获得1.5中的当前角色。 See Pavel's answer about how this will change. 请参阅帕维尔(Pavel)有关此情况将如何变化的答案。 While this may seem inconvenient, I think the reason is that Fabric combines the list of hosts, so role doesn't carry over. 尽管这似乎不方便,但我认为原因是Fabric合并了主机列表,因此角色不会延续。

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

[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. 不完全是您所追求的……但是可能会帮助您找到可行的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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