Pfoef,描述我手头的问题相当困难。请耐心等待。
我有一句格言:
my_dict:
FIRST:
some_key: first_value
SECOND:
some_key: second_value
我的可靠任务是:
- shell: "echo {{ item.value['some_key'] }}"
register: exec_output
loop: "{{ my_dict | dict2items }}"
# This is something where I do not know what to do
- set_fact:
desired_output: ???
when: <some_key_contains_a_value>
当Ansible执行时,它将执行shell命令两次,因为dict.中有2项
Q:如果some_key的值为"SECOND_value",我如何配置Ansible,以便:Ansible将设置一个事实并添加密钥(FIRST或SECOND(。在该示例情况下,该事实将包含";第二";。
当register
通过item.item
属性输出时,您可以找到作为循环一部分的整个item
。
因此,在您的案例中,您会发现,在exec_output.results
下的项目中:
item: key: FIRST value: some_key: first_value
item: key: SECOND value: some_key: second_value
因此,基于此,您可以有一个类似于的剧本
- hosts: localhost
gather_facts: no
tasks:
- shell: "echo {{ item.value.some_key }}"
register: exec_output
loop: "{{ my_dict | dict2items }}"
vars:
my_dict:
FIRST:
some_key: first_value
SECOND:
some_key: second_value
- set_fact:
desired_output: "{{ item.item.key }}"
when: some_key in item.stdout
loop: "{{ exec_output.results }}"
vars:
some_key: second
loop_control:
label: "{{ item.stdout }}"
- debug:
var: desired_output
这将给你带来预期的结果:
PLAY [localhost] *******************************************************************************************************************
TASK [shell] ***********************************************************************************************************************
changed: [localhost] => (item={'key': 'FIRST', 'value': {'some_key': 'first_value'}})
changed: [localhost] => (item={'key': 'SECOND', 'value': {'some_key': 'second_value'}})
TASK [set_fact] ********************************************************************************************************************
skipping: [localhost] => (item=first_value)
ok: [localhost] => (item=second_value)
TASK [debug] ***********************************************************************************************************************
ok: [localhost] =>
desired_output: SECOND
PLAY RECAP *************************************************************************************************************************
localhost : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0