我有一个简单的剧本,我试图将local_fact文件推送到远程主机,然后根据对本地事实的比较来执行任务。但是事实文件是按预期在远程主机上创建的,但不会被读取
我以为文件创建和读取之间必须有延迟,所以我等待,但要确保在读取文件之前先创建文件
`- hosts: "{{ target }}"
vars:
abc: "10"
xyz: "11"
tasks:
- name: write custom fact
copy:
dest: /etc/ansible/facts.d/somefact_b.fact
owner: root
group: root
mode: 0644
content: |
{'some_var1': {{ abc|int }}}
- name: write custom fact
copy:
dest: /etc/ansible/facts.d/somefact_a.fact
owner: root
group: root
mode: 0644
content: |
{'some_var2': {{ xyz|int }}}
- wait_for:
path: /etc/ansible/facts.d/somefact_b.fact
- wait_for:
path: /etc/ansible/facts.d/somefact_a.fact
- debug: var=ansible_local.somefact_a.some_var1
- debug: var=ansible_local.somefact_b.some_var2
- debug:
msg: "Everything Looks Good"
when: ansible_local.somefact_a.some_var1 != ansible_local.somefact_b.some_var2`
答案 0 :(得分:0)
Q:“如果重新运行相同的剧本,则不会在第一次读取,效果很好。”
A:在同一本剧本中开始新剧本。
- hosts: "{{ target }}"
vars:
abc: "10"
xyz: "11"
tasks:
- name: write custom fact
copy:
...
- hosts: "{{ target }}"
tasks:
- debug: var=ansible_local.somefact_a.some_var1
- debug: var=ansible_local.somefact_b.some_var2
...
例如下面的剧本
- hosts: test_01
tasks:
- copy:
dest: /etc/ansible/facts.d/somefact_a.fact
content: |
{"some_var1": 10}
- hosts: test_01
tasks:
- debug:
var: ansible_local.somefact_a.some_var1
给予
ok: [test_01] => {
"ansible_local.somefact_a.some_var1": "10"
}
注释
1)需要 setup 来读取变量
$ ansible -i hosts test_01 -m setup -a "filter=ansible_local"
test_01 | SUCCESS => {
"ansible_facts": {
"ansible_local": {
"somefact_a": {
"some_var1": 10
}
}
},
"changed": false
}
2)如果没有 setup ,变量将不可用
$ ansible -i hosts test_01 -m debug -a "var=ansible_local"
test_01 | SUCCESS => {
"ansible_local": "VARIABLE IS NOT DEFINED!"
}
3)使用 gather_facts: false
- hosts: test_01
gather_facts: false
tasks:
- debug:
var: ansible_local.somefact_a.some_var1