[英]Loop through a registered variable with with_dict in Ansible
How to refer to elements of dictionary of a registered value. 如何引用注册值字典的元素。
My Ansible playbook look like this : 我的Ansible剧本看起来像这样:
- command: echo {{ item }}
with_dict:
- foo
- bar
- baz
register: echos
Registered variable "echos" will be a dictionary : 注册变量“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"
}
]
} }
Now if i want to refer to "changed" field of "foo" dictionary element of echos dictionary , How do i do that ?? 现在,如果我想引用回声字典的“foo”字典元素的“已更改”字段,我该怎么做?
First of all, your example is flawed: with_dict
can't iterate over list. 首先,你的例子是有缺陷的:
with_dict
不能迭代列表。
But general approach is as follows: 但一般方法如下:
---
- 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 }}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.