我试图遍历字典,我引用了以下线程,但是它不断失败:
How to loop over this dictionary in Ansible?
以下是我的剧本:
- hosts: server_hosts
tasks:
- name: Include dictionary data
include_vars:
file: vars/input_vars.yaml
- name: Show info field from data.yml
debug:
msg: "Id: {{ input_data[item]['version'] }} - info: {{ input_data[item]['name'] }}"
with_items: "{{ input_data.keys() }}"
input_data:
item_1:
name: "test1"
version: "18.3"
item_2:
name: "test2"
version: "18.3"
item_3:
name: "test3"
version: "18.3"
执行剧本时,它失败并显示以下错误:
fatal: [192.168.16.120]: FAILED! => {
"ansible_facts": {},
"ansible_included_var_files": [],
"changed": false,
"message": "Syntax Error while loading YAML.\n mapping values are not allowed here\n\nThe error appears to have been in '/git_projects/base/vars/input_vars.yaml': line 2, column 12, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n----\n input_data:\n ^ here\n"
}
答案 0 :(得分:0)
我已经对其进行了测试,并且可以正常运行,还从input_vars.yaml
➜ ~ cat input_vars.yaml
input_data:
item_1:
name: "test1"
version: "18.3"
item_2:
name: "test2"
version: "18.3"
item_3:
name: "test3"
version: "18.3"
➜ ~ cat example.yml
---
- hosts: localhost
tasks:
- name: Include dictionary data
include_vars:
file: input_vars.yaml
- name: Show info field from data.yml
debug:
msg: "Id: {{ input_data[item]['version'] }} - info: {{ input_data[item]['name'] }}"
with_items: "{{ input_data.keys() }}"
输出
➜ ~ ansible-playbook example.yml
[WARNING]: Unable to parse /etc/ansible/hosts as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [localhost] ***********************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
ok: [localhost]
TASK [Include dictionary data] *********************************************************************************************************
ok: [localhost]
TASK [Show info field from data.yml] ***************************************************************************************************
ok: [localhost] => (item=item_2) => {
"msg": "Id: 18.3 - info: test2"
}
ok: [localhost] => (item=item_3) => {
"msg": "Id: 18.3 - info: test3"
}
ok: [localhost] => (item=item_1) => {
"msg": "Id: 18.3 - info: test1"
}
PLAY RECAP *****************************************************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0