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

如何将多行YML数组解析为Ansible循环可用的字典

解决方案

1. 确认services.yml结构

假设你的services.yml结构如下:

Groups:
  services:
    Columns:
      - service_name
      - port
      - protocol
    Rows:
      - [ "web", "80", "TCP" ]
      - [ "ssh", "22", "TCP" ]
      - [ "db", "3306", "TCP" ]

2. 数据预处理:将Columns与Rows映射为字典列表

在Ansible Playbook中,先加载变量,再通过set_fact把每行数据和字段名配对成可按键访问的字典:

- name: 加载services配置
  include_vars:
    file: services.yml
    name: service_config

- name: 预处理生成字典格式的服务列表
  set_fact:
    formatted_services: "{{ service_config.Groups.services.Rows | map('zip', service_config.Groups.services.Columns) | map('dict') | list }}"

这里的逻辑是:

  • 用zip把每行的数组元素和Columns里的字段名一一配对
  • 再通过dict把配对后的元组转换成字典
  • 最后用list把所有字典整理成列表

3. 在PowerShell任务中循环调用

现在可以直接循环formatted_services,按键访问每个参数:

- name: 创建Windows防火墙规则
  win_shell: |
    New-NetFirewallRule -DisplayName "{{ item.service_name }}_rule" -Direction Inbound -LocalPort "{{ item.port }}" -Protocol "{{ item.protocol }}" -Action Allow
  loop: "{{ formatted_services }}"

更推荐用Ansible官方的Windows防火墙模块(更规范易维护):

- name: 创建Windows防火墙规则
  win_firewall_rule:
    name: "{{ item.service_name }}_rule"
    direction: inbound
    local_port: "{{ item.port }}"
    protocol: "{{ item.protocol }}"
    action: allow
    state: present
  loop: "{{ formatted_services }}"

4. 调试验证(可选)

如果不确定预处理结果,可以加个调试任务确认:

- name: 查看格式化后的服务列表
  debug:
    var: formatted_services

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 17:24:54