使用寄存器变量存储多主机播放的值

时间:2017-06-20 08:45:26

标签: ansible

我有一个包含两个剧本的ansible剧本,第一个剧本的输出将由第二个使用。所以我使用寄存器变量来存储输出。问题是我的游戏是打算在多个主机而不是单个主机上工作,每次都会覆盖寄存器的输出,而且我没有最后(n-1)次执行的值。

我的剧本看起来像这样:

- name: Perform task 
  hosts:  db_server
  connection: local
  gather_facts: no
  vars:
    - method: "{{ method }}"

  roles:
    - {role: run_custom_module, tags: ["maintenance"]}


- name: Second task based on output of first
  hosts:  db_server
  connection: local
  gather_facts: no
  vars:
    - method: "{{ method }}"

  roles:
    - {role: run_custom_module, when: result=="some_string"}

run_custom_module的作用如下所示:

- name: Executing the custom module
  run_custom_module:
      task: "Run custom py module"
      var: "{{ method }}"
  register: result

清单文件如下:

[db_server]
1.1.1.1
2.2.2.2
3.3.3.3

对于with_items,寄存器变量将输出存储在名为 results 的列表中,请参考here。基于类似的理由,我如何将多主机播放的输出存储在寄存器变量中,以便它可以在同一剧本的第二次播放中使用?

1 个答案:

答案 0 :(得分:1)

注册变量是事实。您可以使用hostvars访问其他主机上的事实。

例如,您可以使用result访问主机1.1.1.1的{​​{1}}注册变量。

您可以使用hostvars['1.1.1.1'].result列出组中的所有主机。

例如,您可以使用groups列出db_server组中的所有主机。

要结束,你可以尝试这样的事情:

groups['db_server']