Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

amazon web services - Ansible lookup values from complex structure?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...