如果数组元素与 Ansible 中的值匹配,则获取数组变量名称
我想获取数组名称(如 DNS_One
、NTP
等),如果特定键值(此处为 cidr
)来自输入文件匹配。
我已尝试使用以下剧本,但这会导致错误。
Input.yaml:
[
{
"id": "111177789966",
"cidr": "10.10.10.10/24"
},
{
"id": "13215464897",
"cidr": "10.100.100.0/24"
}
]
Input_var.yaml:
---
Stores:
- name: "Test1"
DNS_One:
- "10.10.10.10/24"
- "192.168.1.1/24"
DNS_One-HO:
- "10.20.25.100"
- "10.100.100.0/24"
- name: "Test2"
DNS_One:
- "10.20.10.10/24"
预期输出:
[
{
"id": "111177789966",
"cidr": "10.10.10.10/24",
"net_name": "DNS_One"
},
{
"id": "13215464897",
"cidr": "10.100.100.0/24",
"net_name": "DNS_One-HO"
}
]
Playbook:
- name: Search
vars:
test-merge: >-
{{
input_var
| selectattr('name', 'eq', Test1 | string )
| map(attribute= item)
| first
| default([])
}}
set_fact:
po_g: >-
{{
po_g | default([]) +
[{
'id': item.id,
'cidr': item.cidr,
'subnetname': test-merge
}]
}}
loop: "{{ input }}"
I would like to to get the array name (like DNS_One
, NTP
, etc.), if a particular key value (here cidr
) from an input file matches.
I have tried with the below playbook, but that is causing errors.
Input.yaml:
[
{
"id": "111177789966",
"cidr": "10.10.10.10/24"
},
{
"id": "13215464897",
"cidr": "10.100.100.0/24"
}
]
Input_var.yaml:
---
Stores:
- name: "Test1"
DNS_One:
- "10.10.10.10/24"
- "192.168.1.1/24"
DNS_One-HO:
- "10.20.25.100"
- "10.100.100.0/24"
- name: "Test2"
DNS_One:
- "10.20.10.10/24"
Expected output:
[
{
"id": "111177789966",
"cidr": "10.10.10.10/24",
"net_name": "DNS_One"
},
{
"id": "13215464897",
"cidr": "10.100.100.0/24",
"net_name": "DNS_One-HO"
}
]
Playbook:
- name: Search
vars:
test-merge: >-
{{
input_var
| selectattr('name', 'eq', Test1 | string )
| map(attribute= item)
| first
| default([])
}}
set_fact:
po_g: >-
{{
po_g | default([]) +
[{
'id': item.id,
'cidr': item.cidr,
'subnetname': test-merge
}]
}}
loop: "{{ input }}"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用
dict2items< /code>
位于
input_var.Stores
列表的元素上,以使其更具可查询性。您可以在地图
。然后你回到你想要做的事情,
selectattr
获取与当前循环的输入项的 CIDR 相对应的元素。在列表上,这可以借助包含
Ansible 在 Jinja 内置测试之上提供的测试。最终结果是
set_fact
:根据剧本:
这会产生:
You will have to use
dict2items
on the elements of yourinput_var.Stores
list, in order to make it more queryable. You can apply this filter on all the items of the list, with the help ofmap
.Then you fall back to what you where trying to do, a
selectattr
to fetch the element that correspond to the CIDR of the input item your are currently looping on. On a list, this can be achieved with the help of thecontains
test that Ansible provides on top on Jinja builtin tests.Which ends up in this
set_fact
:Given the playbook:
This yields: