来自复杂结构的 Ansible 查找值? [英] Ansible lookup values from complex structure?
问题描述
我正在编写 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 =>使用
字典,但我对替代方案感兴趣.ec2_vpc_subnet_facts
结果中的 set_facts
的子网 ID
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.
问候,奥拉
推荐答案
selectattr 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 查找值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!