我有没有办法从playbook任务中传递/更新组变量?我需要根据来自一个主机的某些命令的结果来定义变量,以将它们用于其他角色和任务。我知道set_fact但是它将变量存储为局部变量,因此我需要寻址特定的主机来获取它,但是这个主机的主机名/地址可能会有所不同。谷歌搜索和阅读docs.ansible.com仍然没有帮助。
UPD:有两个不同的角色一个接一个地播放任务,我需要在播放之间传递变量。
一个选项是使用ansible模块lineinfile,blockinfile,template和ini_file来更新group variables。
例如下面的剧本
- hosts: test_jails
gather_facts: false
vars:
my_groupvar_file: "{{ inventory_dir }}/group_vars/test_jails.yml"
tasks:
- debug:
var: my_last_run
- block:
- command: date "+%F %T"
register: result
- lineinfile:
path: "{{ my_groupvar_file }}"
regexp: "^my_last_run: "
line: "my_last_run: {{ result.stdout }}"
backup: yes
delegate_to: localhost
run_once: true
组变量group_vars / test_jails.yml
my_last_run: 2019-04-19 11:51:00
给(删节):
> ansible-playbook test1.yml
PLAY [test_jails]
TASK [debug]
ok: [test_01] => {
"my_last_run": "2019-04-19 11:51:00"
}
ok: [test_03] => {
"my_last_run": "2019-04-19 11:51:00"
}
ok: [test_02] => {
"my_last_run": "2019-04-19 11:51:00"
}
TASK [command]
changed: [test_01]
TASK [lineinfile]
changed: [test_01 -> localhost]
PLAY RECAP
test_01 : ok=3 changed=2 unreachable=0 failed=0
test_02 : ok=1 changed=0 unreachable=0 failed=0
test_03 : ok=1 changed=0 unreachable=0 failed=0
> cat group_vars/test_jails.yml
my_last_run: 2019-04-19 11:56:51