如何解决Ansible:多循环到 json 文件
我有一个包含 NetworkFlow 键列表的 json 文件作为源,我想从中提取信息以创建安全规则,在 ansible 中使用双循环。
下面是我的 json 文件中的一个例子:
{
"Name":"Some_name","NetworkFlow":[
{
"GroupName":"Test1","Type":"Ingress","Env":"prod","Server":[
"192.168.1.1","192.168.1.2"
],"Service":[
{
"Protocol":"TCP","Port":"443,22,53"
},{
"Protocol":"UDP","Port":"21"
}
]
},{
"GroupName":"Test2","Type":"Egress","Env":"dev","Server":[
"192.168.1.3","192.168.1.4"
],"Service":[
{
"Protocol":"UDP","Port":"9996,9997"
}
]
}
]
}
所以首先我必须为每个 NetworkFlow 部分循环,在每个部分中,我必须在 servers 列表和 列表中循环>services(协议和端口)以获得类似如下的解析:
#rule= Server,Protocol,Port,Type,Env,GroupName
msg: 192.168.1.1,TCP,443,Ingress,prod,Test1
msg: 192.168.1.1,53,UDP,21,Test1
msg: 192.168.1.2,Test1
msg: 192.168.1.3,9996,Egress,dev,Test2
msg: 192.168.1.3,9997,Test2
msg: 192.168.1.4,Test2
在我的剧本任务下面:
我的主要任务:
---
- name: Include JSON file
include_vars:
file: test.json
- include_tasks: rules.yml
loop: "{{ NetworkFlow }}"
loop_control:
loop_var: oi
我的规则任务:
---
- 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
有关信息,我的 oi.Service.Port 可以有一个以逗号分隔的端口列表!
我尝试在 with_nested 内使用 loop 并且它适用于第一个键 Test1,但我没有得到正确的解析对于第二个 NetworkFlow 键 Test2
TASK [test : set_fact] *****************************************************************************************************************************************
ok: [localhost]
TASK [test : debug] ********************************************************************************************************************************************
"msg": "192.168.1.1,Test1"
"msg": "192.168.1.1,Test1"
"msg": "192.168.1.2,Test1"
}
TASK [test : set_fact] *****************************************************************************************************************************************
ok: [localhost]
TASK [test : debug] ********************************************************************************************************************************************
"msg": "192.168.1.3,Test2"
"msg": "192.168.1.3,Test2"
"msg": "192.168.1.4,Test2"
有人知道如何处理吗?
解决方法
下面的任务创建列表服务,包括服务器
- set_fact:
Services: "{{ Services|default([]) + Service|from_yaml }}"
vars:
Service: |
{% for Port in item.1.Port.split(',') %}
- {{ item.0 }},{{ item.1.Protocol }},{{ Port }},{{ oi.Type }},{{ oi.Env }},{{ oi.GroupName }}
{% endfor %}
with_nested:
- "{{ oi.Server }}"
- "{{ oi.Service }}"
Services:
- 192.168.1.1,TCP,443,Ingress,prod,Test1
- 192.168.1.1,22,53,UDP,21,Test1
- 192.168.1.2,Test1
- 192.168.1.3,9996,Egress,dev,Test2
- 192.168.1.3,9997,Test2
- 192.168.1.4,Test2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。