如果嵌套数组中不存在嵌套值,则为

时间:2018-12-13 17:51:51

标签: ansible-facts

我想使Ansible EIP创建成为幂等。为了做到这一点,我只希望任务在标签“名称”值“ tag_1”不存在时运行。 但是我不确定如何在任务结束时将其添加为“何时”。

    "eip_facts.addresses": [
    {
        "allocation_id": "eipalloc-blablah1", 
        "domain": "vpc", 
        "public_ip": "11.11.11.11", 
        "tags": {
            "Name": "tag_1", 
        }
    }, 
    {
        "allocation_id": "eipalloc-blablah2", 
        "domain": "vpc", 
        "public_ip": "22.22.22.22", 
        "tags": {
            "Name": "tag_2", 
        }
    }, 
    {
        "allocation_id": "eipalloc-blablah3", 
        "domain": "vpc", 
        "public_ip": "33.33.33.33", 
        "tags": {
            "Name": "tag_3", 
        }
    }
]

(稍后添加标签)我正在寻找类似的东西:

- name: create elastic ip 
  ec2_eip:
    region: eu-west-1
    in_vpc: yes
  when: eip_facts.addresses[].tags.Name = "tag_1" is not defined

实现此目标的正确方法是什么?请记住,该值不能存在于整个数组的该参数中,而不仅仅是单个迭代。

1 个答案:

答案 0 :(得分:0)

好,我找到了一个不错的解决方案

- name: Get list of EIP Name Tags
  set_fact:
    eip_facts_Name_tag: "{{ eip_facts.addresses | map(attribute='tags.Name') | list }}"

提取Name标签并将其放入数组

ok: [localhost] => {
"msg": [
    "tag_1", 
    "tag_2", 
    "tag_3"
  ]
}

然后...

- debug: 
    msg: "Hello"
  when: '"tag_1" in "{{ eip_facts_Name_tag }}"'

这将起作用,但是请注意,这不会进行精确的字符串搜索。因此,如果您只搜索“标签”,那么这也算是匹配。