在 Ansible 中使用 with_dict 循环注册变量 [英] Loop through a registered variable with with_dict in Ansible

查看:36
本文介绍了在 Ansible 中使用 with_dict 循环注册变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何引用已注册值的字典元素.

How to refer to elements of dictionary of a registered value.

我的 Ansible 手册如下所示:

My Ansible playbook look like this :

- command: echo {{ item }}
  with_dict:
    - foo
    - bar
    - baz
  register: echos

注册变量echos"将是一个字典:

Registered variable "echos" will be a dictionary :

 {

"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 字典的foo"字典元素的已更改"字段,我该怎么做??

Now if i want to refer to "changed" field of "foo" dictionary element of echos dictionary , How do i do that ??

推荐答案

首先,您的示例存在缺陷:with_dict 无法遍历列表.

First of all, your example is flawed: with_dict can't iterate over list.

但一般的做法如下:

---
- 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 }}'

这篇关于在 Ansible 中使用 with_dict 循环注册变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆