如何解决Ansible:双循环到 json 文件
我有一个包含块和数据列表的 json 文件作为源。我想从中提取信息来创建安全规则,在 ansible 中使用双循环。
下面是我的 json 文件中的一个例子:
[
{
"Name":"Some_name","NetworkFlow":[
{
"GroupName":"Test1","Type":"Ingress","Env":"dev","Server":[
"192.168.1.1","192.168.1.2",...
],"Service":[
{
"Protocol":"TCP","Port":"443"
},{
"Protocol":"UDP","Port":"21"
},....
]
},....
]
}
]
这是针对通用部署,对于每个“NetworkFlow”部分,我必须在服务器列表以及协议和端口列表中循环,以获得如下所示的模拟解析:
#rule= Server,Protocol,Port,Type,Env,GroupName
192.168.1.1,TCP,443,Ingress,Dev,Test1
192.168.1.2,Test1
192.168.1.1,UDP,21,Test1
我试过 with_nested 但它不起作用,请问有什么办法解决吗?
解决方法
用嵌套循环创建一个文件,例如
shell> cat rules.yml
- debug:
msg: "{{ item.0 }},{{ item.1.Protocol }},{{ item.1.Port }},{{ outer_item.Type }},{{ outer_item.Env }},{{ outer_item.GroupName }}"
with_nested:
- "{{ outer_item.Server }}"
- "{{ outer_item.Service }}"
并包含它
- include_tasks: rules.yml
loop: "{{ NetworkFlow }}"
loop_control:
loop_var: outer_item
给予
msg: 192.168.1.1,TCP,443,Ingress,dev,Test1
msg: 192.168.1.1,UDP,21,Test1
msg: 192.168.1.2,Test1
问:“...有一个由逗号分隔的端口列表,而不仅仅是一个端口。”
A:转换数据。例如
shell> cat rules.yml
- set_fact:
Services: "{{ Services|from_yaml }}"
vars:
Services: |
{% for service in oi.Service %}
{% for port in service.Port.split(',') %}
- Protocol: {{ service.Protocol }}
Port: {{ port }}
{% endfor %}
{% endfor %}
- debug:
msg: "{{ i.0 }},{{ i.1.Protocol }},{{ i.1.Port }},{{ oi.Type }},{{ oi.Env }},{{ oi.GroupName }}"
with_nested:
- "{{ oi.Server }}"
- "{{ Services }}"
loop_control:
loop_var: I
给予
msg: 192.168.1.1,22,53,Test1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。