Ansible lookup values from complex structure?

大憨熊 提交于 2019-11-26 21:44:51

问题


I'm working on an Ansible playbook where I use the ec2_vpc_subnet_facts to register facts about subnets in a VPC like:

- ec2_vpc_subnet_facts:
    region: "{{ ec2_region }}"
    filters:
      vpc-id: "{{ vpc.vpc.id }}"
  register: vpc_subnet_facts

thus getting back a structure like (removed irrelevant attributes):

"vpc_subnet_facts": {
    "changed": false,
    "subnets": [
        {
            ...
            "id": "subnet-0bb50753",
            ...
            "tags": {
                "Name": "mytag1"
            },
            ...
        },
        {
            ...
            "id": "subnet-0bb50754",
            ...
            "tags": {
                "Name": "mytag2"
            },
            ...
        }
    ]
}

Later in the playbook, when creating the EC2 instances the idea is to lookup a subnet ID based on tag value for the ec2modules vpc_subnet_idattribute, i.e. having mytag1 looking up the associated subnet ID subnet-0bb50753.

My current approach is to create a tag => subnet-ID dictionary using set_facts from the ec2_vpc_subnet_facts result but I'm interested in alternatives.

Regards, Ola


回答1:


selectattr jinja filter is your friend here:

- debug: msg="{{ (vpc_subnet_facts.subnets | selectattr('tags.Name','equalto','mytag1') | first).id }}"

What is done here: make a subset of elements from vpc_subnet_facts.subnets where tags.Name=='mytag1', take first element, take id field.



来源:https://stackoverflow.com/questions/39685255/ansible-lookup-values-from-complex-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!