从外部主机文件设置结构主机列表

sie*_*sta 4 python fabric

我需要通过打开和读取文件来获取主机来获取结构来设置其主机列表.以这种方式设置允许我拥有一个庞大的主机列表,而无需每次都为这些数据编辑我的fabfile.

我试过这个:

def set_hosts():
    env.hosts = [line.split(',') for line in open("host_file")]

def uname():
    run("uname -a")
Run Code Online (Sandbox Code Playgroud)

def set_hosts():
    env.hosts = open('hosts_file', 'r').readlines

def uname():
    run("uname -a")
Run Code Online (Sandbox Code Playgroud)

每次我尝试使用函数set_hosts时,我都会收到以下错误:

fab set_hosts uname
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/fabric/main.py", line 712, in main
    *args, **kwargs
  File "/usr/local/lib/python2.7/dist-packages/fabric/tasks.py", line 264, in execute
    my_env['all_hosts'] = task.get_hosts(hosts, roles, exclude_hosts, state.env)
  File "/usr/local/lib/python2.7/dist-packages/fabric/tasks.py", line 74, in get_hosts
    return merge(*env_vars)
  File "/usr/local/lib/python2.7/dist-packages/fabric/task_utils.py", line 57, in merge
    cleaned_hosts = [x.strip() for x in list(hosts) + list(role_hosts)]
AttributeError: 'builtin_function_or_method' object has no attribute 'strip'
Run Code Online (Sandbox Code Playgroud)

spi*_*lok 15

您在这里遇到的问题是您将env.hosts设置为函数对象,而不是列表或可迭代.你需要在readlines之后的parens来实际调用它:

def set_hosts():
    env.hosts = open('hosts_file', 'r').readlines()
Run Code Online (Sandbox Code Playgroud)

  • +1,表示面料只是python. (3认同)