问题描述
我正在研究Ansible剧本,在其中我使用 ec2_vpc_subnet_facts
在VPC中注册有关子网的事实,例如:
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"
},
...
}
]
}
在剧本中,稍后,在创建EC2实例时,其想法是根据 ec2
modules vpc_subnet_id的标签值查找子网ID。
属性,即让 mytag1
查找关联的子网ID subnet-0bb50753
。
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
.
我当前的方法是创建 tag =>子网ID
字典,它使用来自 ec2_vpc_subnet_facts
结果的 set_facts
,但我对替代方法感兴趣。
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.
问候,奥拉
推荐答案
jinja过滤器是您的朋友:
selectattr jinja filter is your friend here:
- debug: msg="{{ (vpc_subnet_facts.subnets | selectattr('tags.Name','equalto','mytag1') | first).id }}"
此处完成的工作:从 vpc_subnet_facts.subnets ,其中
tags.Name =='mytag1'
,采用第一个元素,采用 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.
这篇关于来自复杂结构的Ansible查找值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!