ansible 运行全局变量

doh*_*utz 8 ansible ansible-playbook

我想使用 ansible 创建一个服务器集群。

在一本主要剧本中,我包含了一些子剧本。

- include: playbook_commandserver.yml
- include: playbook_agent.yml
Run Code Online (Sandbox Code Playgroud)

在 playbook_commandserver.yml 中,我创建了命令服务器(在 aws 上)。然后,我触发了一个角色,该角色使用该set_fact模块来记住命令服务器的 dns 名称:

- name: Get hostname of command server
  shell: /usr/bin/host $(/usr/bin/curl -s http://ipecho.net/plain) | /usr/bin/awk '{print $5}' | /usr/bin/awk -F 'aws.com' '{print $1"aws.com"}'
  register: cs
- name: Set hostname of command server as fact
  set_fact: commandserver="{{ cs.stdout }}"
Run Code Online (Sandbox Code Playgroud)

commandserver事实是在同一操作可用,但不是在同一个剧本..更何况是在playbook_agent.yml,这是包含,算账。它就在那里,我需要在那里访问该命令服务器事实。

那么如何设置/存储对完整的 ansible-run 有效的变量呢?

我发现了这个:https : //stackoverflow.com/questions/26732241/ansible-save-registered-variable-to-file 但是对我来说这看起来像一个丑陋的黑客。

这个问题有没有更好的解决方案?有没有办法设置一个对整个 ansible-run 有效的变量?

小智 13

是的,这是可能的。当您使用set_fact模块设置事实时,可以通过“hostvars”访问该事实。因此,如果您像这样定义变量 commandserver:

  - name: Set hostname of command server as fact
    set_fact: commandserver="{{ cs.stdout }}"
Run Code Online (Sandbox Code Playgroud)

然后您可以通过这种方式在其他包含的相同剧本的剧本中访问此变量(调试模块只是一个示例):

  - debug: msg="{{ hostvars['put the hostname in here']['commandserver'] }}"
Run Code Online (Sandbox Code Playgroud)