首页 > 解决方案 > with_items 中的多个变量出错

问题描述

我创建了以下剧本来设置 ufw 设置。

---
- name: setup ufw for multi ports
  hosts: db
  become: yes

  tasks:
  - name: 'Allow all access for multi ports'
    community.general.ufw:
            rule: allow
            port: "{{ item.port_num }}"
            src: "{{ item.dest_ip }}"
    with_items:
            - { port_num: "33787", dest_ip: "{{web_ip_band}}" }

这是我的group_vars文件。

web_ip_band:
  - '192.168.101.13/24'
  - '192.168.101.44/24'

当我执行这个剧本时,我得到了这个错误。

失败:[dbserver01] (item={'port_num': '33787', 'dest_ip': ['192.168.101.13/24', '192.168.101.44/24']}) => {"ansible_loop_var": "item" , "已更改": false, "命令": ["/usr/sbin/ufw 状态详细", "/bin/grep -h '^### tuple' /lib/ufw/user.rules /lib/ufw/ user6.rules /etc/ufw/user.rules /etc/ufw/user6.rules /var/lib/ufw/user.rules /var/lib/ufw/user6.rules", "/usr/sbin/ufw -- version", "/usr/sbin/ufw 允许从 ['192.168.101.13/24', '192.168.101.44/24'] 到任何端口 33787"], "item": {"dest_ip": ["192.168.101.13 /24", "192.168.101.44/24"], "port_num": "33787"}, "msg": "错误:参数数量错误\n"}

我的剧本中是否存在语法错误?

标签: ansibleyaml

解决方案


来自community.general.ufw模块文档(重新排列以适合 SO 答案的提取物)

from_ip (别名: from, src )

字符串- 默认值:“任何”

您正在传递一个IP列表,它解释了您的错误消息:

错误:参数数量错误

您必须为 中的每个条目组合port_num和单个条目执行该任务dest_ip。你需要的是一个子元素循环

 - name: 'Allow all access for multi ports'
   community.general.ufw:
     rule: allow
     port: "{{ item.0.port_num }}"
     src: "{{ item.1 }}"
    vars:
      my_rules:
        - { port_num: "33787", dest_ip: "{{web_ip_band}}" }
    loop: "{{ my_rules | subelements('dest_ip') }}"
           

推荐阅读