Loops 循环使用Ansible中的_dict遍历已注册变量
如何引用注册值字典的元素 我的Ansible剧本如下所示:Loops 循环使用Ansible中的_dict遍历已注册变量,loops,dictionary,ansible,Loops,Dictionary,Ansible,如何引用注册值字典的元素 我的Ansible剧本如下所示: - command: echo {{ item }} with_dict: - foo - bar - baz register: echos 注册变量“echos”将是一个字典: { "changed": true, "msg": "All items completed", "results": [ { "changed": true, "cmd": [
- command: echo {{ item }}
with_dict:
- foo
- bar
- baz
register: echos
注册变量“echos”将是一个字典:
{
"changed": true,
"msg": "All items completed",
"results": [
{
"changed": true,
"cmd": [
"echo",
"foo"
],
"delta": "0:00:00.002780",
"end": "2014-06-08 16:57:52.843478",
"invocation": {
"module_args": "echo foo",
"module_name": "command"
},
"item": "foo",
"rc": 0,
"start": "2014-06-08 16:57:52.840698",
"stderr": "",
"stdout": "foo"
},
{
"changed": true,
"cmd": [
"echo",
"bar"
],
"delta": "0:00:00.002736",
"end": "2014-06-08 16:57:52.911243",
"invocation": {
"module_args": "echo bar",
"module_name": "command"
},
"item": "bar",
"rc": 0,
"start": "2014-06-08 16:57:52.908507",
"stderr": "",
"stdout": "bar"
},
{
"changed": true,
"cmd": [
"echo",
"baz"
],
"delta": "0:00:00.003050",
"end": "2014-06-08 16:57:52.979928",
"invocation": {
"module_args": "echo baz",
"module_name": "command"
},
"item": "baz",
"rc": 0,
"start": "2014-06-08 16:57:52.976878",
"stderr": "",
"stdout": "baz"
}
]
}
现在,如果我想引用echos dictionary的“foo”dictionary元素的“changed”字段,我该如何做???首先,您的示例有缺陷:
with_dict
无法在列表上迭代
但一般做法如下:
---
- hosts: localhost
gather_facts: no
tasks:
- command: echo {{ item }}
with_items:
- foo
- bar
- baz
register: echos
# Iterate all results
- debug: msg='name {{ item.item }}, changed {{ item.changed }}'
with_items: '{{ echos.results }}'
# Select 'changed' attribute from 'foo' element
- debug: msg='foo changed? {{ echos.results | selectattr("item","equalto","foo") | map(attribute="changed") | first }}'