如何在ansible中将主机与变量配对

gk_*_*000 2 ansible ansible-inventory

我有一个库存,例如:

all:
  children:
    server_group1:
      hosts:
        host1:
    server_group2:
      children:
        app1:
          hosts:
            host2:
            host3:
        app2:
          hosts:
            host4:
            host5:
    server_group3:
...
Run Code Online (Sandbox Code Playgroud)

我已经像这样组织了我的服务器变量:

我试图以该组的名字命名我的字典(从而使它们独一无二)并在我的剧本中访问它:

hosts: server_group2
tasks:
  - name: check file
    local_action: stat path=path/to/test/{{hostvars[0].name1}}
    register: payld_txt

  - name: conditional transfer
    copy:
      src: path/to/test/{{hostvars[0].name1}}
      dest: /svr/path/{{hostvars[0].name2}}
    when: payld_txt.stat.exists
Run Code Online (Sandbox Code Playgroud)

我最终遇到了这个错误:

该任务包含一个带有未定义变量的选项。错误是:“name1”未定义

我哪里错了?

Zei*_*tor 6

在继续之前,您需要修复不尊重 yaml 源的 ansible 结构的清单。下面的简单命令可以给您一些提示:

$ ansible -i inventories/test.yml all --list-hosts
 [WARNING]: Skipping unexpected key (server_group1) in group (all), only "vars", "children" and "hosts" are valid

 [WARNING]: Skipping unexpected key (server_group2) in group (all), only "vars", "children" and "hosts" are valid

 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

  hosts (0):
Run Code Online (Sandbox Code Playgroud)

正确的语法是:

$ ansible -i inventories/test.yml all --list-hosts
 [WARNING]: Skipping unexpected key (server_group1) in group (all), only "vars", "children" and "hosts" are valid

 [WARNING]: Skipping unexpected key (server_group2) in group (all), only "vars", "children" and "hosts" are valid

 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

  hosts (0):
Run Code Online (Sandbox Code Playgroud)

现在给出:

$ ansible -i inventories/test.yml all --list-hosts
  hosts (5):
    host1
    host2
    host3
    host4
    host5
Run Code Online (Sandbox Code Playgroud)