loops - 如何在 Ansible uri 模块中使用正确的循环

标签 loops ansible pfsense

我正在使用Ansible uri module触发pfSense API 。 现在我想在任务中创建防火墙规则(代码被截断)。

---
# tasks file for creating firewall rules

- name: "Create firewall rules"
  uri:
    url: "https://{{ pf_hostname }}/api/v1/firewall/rule"
    method: "POST"
    body: "{ \
          \"client-id\": \"{{ pf_user }}\", 
            \"client-token\": \"{{ pf_password }}\",
            \"type\": \"{{ pf_fw_type_01 }}\",
            \"interface\": \"{{ pf_fw_interface_01 }}\",
          }"

vars 文件如下所示。

---
# vars file for creating firewall rules

# Authentication
pf_hostname: "pfsense.local"
pf_user: "admin"
pf_password: "pfsense"

# Rule 01
pf_fw_type_01: "pass"
pf_fw_interface_01: "wan"

我现在如何重复该任务,而不会为其他规则带来不必要的冗余(例如,使用循环)? 我只提出了以下想法,但对我来说似乎并不理想。

  loop: 
    - "{{ item.client-id: {{ pf_user }}, item.type: {{ pf_fw_type_01 }} }}"
    - "{{ item.client-id: {{ pf_user }}, item.type: {{ pf_fw_type_02 }} }}"

最佳答案

将规则作为动态参数放入列表中怎么样?
例如,就像这样。

vars.yml

---
# vars file for creating firewall rules

# Authentication
pf_hostname: "pfsense.local"
pf_user: "admin"
pf_password: "pfsense"

rules:
  - num: 01
    type: "pass"
    pf_fw_interface: "wan"

  - num: 02
    type: "pass"
    pf_fw_interface: "wan"

剧本

---
- hosts: localhost
  gather_facts: false
  vars_files:
    - vars.yml
  tasks:
    - debug:
        msg: |
          {
            "client-id": "{{ pf_user }}",
            "client-token": "{{ pf_password }}",
            "type": "{{ item.type }}",
            "interface": "{{ item.pf_fw_interface }}"
          }
      loop: "{{ rules }}"

结果

$ ansible-playbook main.yml
(snip)

PLAY [localhost] *********************************************************************************************************************************************************************

TASK [debug] *************************************************************************************************************************************************************************
ok: [localhost] => (item={'type': 'pass', 'pf_fw_interface': 'wan'}) => {
    "msg": {
        "client-id": "admin",
        "client-token": "pfsense",
        "interface": "wan",
        "type": "pass"
    }
}
ok: [localhost] => (item={'type': 'pass', 'pf_fw_interface': 'wan'}) => {
    "msg": {
        "client-id": "admin",
        "client-token": "pfsense",
        "interface": "wan",
        "type": "pass"
    }
}
(snip)

关于loops - 如何在 Ansible uri 模块中使用正确的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65898910/

相关文章:

javascript - 在 For 循环中定时打开不同页面

ansible - 使用 Ansible 导入/添加 yum .repo 文件

sublimetext3 - Ansible Vault 不使用 Sublime Text 保存更改

redirect - pfsense haproxy 重定向与 url 不匹配

ssl - PFSense OpenVPN TLS 握手失败

linux - Linux Fedora 26中如何使用samba挂载共享文件夹

java - 循环遍历列表并查找字符串是否存在

小型 forloop 上的 Python MemoryError

ruby - 使用 ansible playbook 更改 rvm ruby​​ 版本

Javascript 使用 "typeof"控制多种类型,不使用 "if"