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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...