You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整Ansible中AWS ec2_security_group的安全组数据输出格式

Ansible:将安全组结果转换为指定字典列表格式

我在创建VPC、安全组并准备创建虚拟机的过程中,现有代码能成功提取安全组ID和名称,但输出是嵌套列表格式,需要转换为包含group_id和group_name键的字典列表,以便后续虚拟机创建使用。

原代码输出:

"sg_groups": [
    [
        "sg-08xxxxxxxxxxxxxxxx",
        "test1"
    ],
    [
        "sg-05xxxxxxxxxxxxxxxx",
        "test2"
    ]
]

期望输出:

"sg_groups": [
    {
        "group_id": "sg-08xxxxxxxxxxxxxx",
        "group_name": "test1"
    },
    {
        "group_id": "sg-05xxxxxxxxxxxxxx",
        "group_name": "test2"
    }
]

方法:使用json_query直接构造目标格式

替换原有的Extract group_id and group_name任务,利用Ansible的json_query过滤器,直接从注册结果中提取字段并生成字典列表:

- name: Extract group_id and group_name into target dict format
  set_fact:
    sg_groups: "{{ create_sg_output.results | json_query('[].{group_id: group_id, group_name: group_name}') }}"

完整修改后的任务片段

- name: "Configuring security groups for VPC {{ vpc_id }}"
      amazon.aws.ec2_security_group:
        name: "{{ item.value.name }}"
        description: "{{ item.value.description }}"
        tags:
          Name: "{{ item.value.name }}"
        state: present
        vpc_id: "{{ vpc_id }}"
        region: "{{ aws_region }}"
      loop: "{{ query('dict', vpc_security_groups) }}"
      register: "create_sg_output"

      vars:
        vpc_security_groups:
          private_test1:
            name: "test1"
            description: "Allow all connections"
          private_test2:
            name: "test2"
            description: "Allow all connections"


    - name: Extract group_id and group_name into target dict format
      set_fact:
        sg_groups: "{{ create_sg_output.results | json_query('[].{group_id: group_id, group_name: group_name}') }}"

    - name: Display extracted groups
      debug:
        var: sg_groups

原理说明

  • create_sg_output.results是ec2_security_group模块循环执行后返回的结果列表,每个元素包含对应安全组的所有返回字段(包括group_id和group_name)
  • json_query('[].{group_id: group_id, group_name: group_name}')的作用:
    1. []遍历列表中的每个结果元素
    2. {group_id: group_id, group_name: group_name}为每个元素生成新字典,键为指定的group_id和group_name,值对应原结果中的同名字段

替代方案(无jmespath依赖)

如果环境未安装jmespath(json_query依赖库),可以使用community.general集合的工具构造字典:

- name: Extract group_id and group_name into target dict format
  set_fact:
    sg_groups: "{{ create_sg_output.results | map('community.general.dict_kv', 'group_id') | zip(create_sg_output.results | map('community.general.dict_kv', 'group_name')) | map('combine') | list }}"

注:此方案需先安装community.general集合:ansible-galaxy collection install community.general

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 19:12:30