我试图将一个事实从host1传递到host2,但是当ansible到达hosts2时,它返回“未定义的变量”:
- name: some playbook
gather_facts: false
hosts: host1
tasks:
- set_fact:
fact1: "foo"
- hosts: host2
gather_facts: false
tasks:
- debug:
msg: "{{ fact1 }}"
set_fact
模块设置主机变量,您可以使用hostvars
访问这些变量。
- name: some playbook
gather_facts: no
hosts: host1
tasks:
- set_fact:
fact1: "foo"
- hosts: host2
gather_facts: no
tasks:
- debug:
msg: "{{ hostvars['host1']['fact1'] }}"
一般来说,这个用例可以通过三个步骤来解决。创建、共享和使用变量。例如,给定库存
shell> cat hosts
host1
host2
剧本按预期工作
- name: Run single host and create facts
hosts: host1
tasks:
- set_fact:
fact1: foo
- name: Share facts among all hosts
hosts: all
tasks:
- set_fact:
fact1: "{{ hostvars.host1.fact1 }}"
run_once: true
- name: Use shared facts
hosts: host2
tasks:
- debug:
var: fact1
如果将用例扩展为“将事实从一组主机传递到另一组主机”,问题是如何有效地共享变量?动态创建剧本。例如,给定库存
shell> cat hosts
host1
host2
host3
host4
让host1和host4创建变量,host2和host3使用它们。创建模板
shell> cat share-vars.yml.j2
- name: Share facts among all hosts
hosts: all
tasks:
- set_fact:
{% for i in share_vars %}
{{ i.var }}: "{{ lbr }} hostvars.{{ i.host }}.{{ i.var }} {{ rbr }}"
{% endfor %}
run_once: true
和剧本
shell> cat create-share-vars.yml
- name: Create playbook share-vars.yml
hosts: localhost
vars:
share_vars:
- {host: host1, var: fact1}
- {host: host4, var: fact4}
lbr: "{{ '{{' }}"
rbr: "{{ '}}' }}"
tasks:
- template:
src: share-vars.yml.j2
dest: share-vars.yml
给予
shell> cat share-vars.yml
- name: Share facts among all hosts
hosts: all
tasks:
- set_fact:
fact1: "{{ hostvars.host1.fact1 }}"
fact4: "{{ hostvars.host4.fact4 }}"
run_once: true
例如导入此剧本
shell> cat playbook.yml
- hosts: host1
tasks:
- set_fact:
fact1: foo
- hosts: host4
tasks:
- set_fact:
fact4: bar
- import_playbook: share-vars.yml
- hosts: host2,host3
tasks:
- debug:
var: fact1
- debug:
var: fact4
给出(删节)
PLAY [host2,host3] *********************************************************
TASK [debug] ***************************************************************
ok: [host2] =>
fact1: foo
ok: [host3] =>
fact1: foo
TASK [debug] ***************************************************************
ok: [host2] =>
fact4: bar
ok: [host3] =>
fact4: bar
注释
TL;博士
加里·洛佩兹的惊人回答。
向认为这有用的人提供更多信息:
请注意,为了引用其他主机的变量,需要先定义它们。
这使得 ansible 可以访问缓存并实际访问这些变量,因为它们是被收集的(例如,收集事实任务是在主机上运行的)。
此信息显示在 Ansible 文档中: https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html#information-about-ansible-magic-variables
使用主机变量,您可以在剧本中的任何位置访问为剧中任何主机定义的变量。您也可以使用 hostvars 变量访问 Ansible 事实,但前提是您已收集(或缓存)事实
因此,请务必在规划剧本时考虑到变量缓存,以便稍后引用它们,就像 Gary Lopez 所写的那样:
- name: First Playbook
gather_facts: no
hosts: host1
tasks:
- set_fact:
fact1: "foo"
- name: Second Playbook
hosts: host2
gather_facts: no
tasks:
- debug:
msg: "{{ hostvars['host1']['fact1'] }}"
我花了一些时间才找到并理解这些信息,可能是由于语言差距:)