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 ec2
modules vpc_subnet_id
attribute, 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
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