我有一个 ansible var :
site1:
- name: myName
value1: something1
value2: apple
value3: 14
...
valuen: "a submarine"
所以关键是,我不知道有多少值。
我想要的输出是:
myName something1 apple 14 a submarine.
(键及其值)
在代码中:
{% for item in site1 %} {% for value in item.name %} {{value}} {% endfor %} {% endfor %}
显然这是行不通的,但是有正确的方法吗?
答案1
迭代字典键并过滤掉不需要的键。
---
- hosts: all
gather_facts: no
vars:
site1:
- name: myName
value1: something1
value2: apple
value3: 14
valuen: "a submarine"
tasks:
- debug:
msg: |
{%- for item in site1 %}
{{item['name']}}
{%- for key in item.keys() | sort %}
{%- if key.startswith('value') %}
{{item[key]}}
{%- endif %}
{%- endfor %}
{%- endfor %}.
结果:
$ ansible-playbook -i localhost, playbook.yml
PLAY [all] ********************************************************************
TASK: [debug ] ****************************************************************
ok: [localhost] => {
"msg": "myName something1 apple 14 a submarine."
}
PLAY RECAP ********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0