ansible任务中的多个循环

时间:2018-10-31 23:30:06

标签: loops ansible

我正在尝试使用vars在ansible中执行循环,但我正在努力使其正常工作。文档讨论了loop属性,但是据我所知,这仅在任务中有一个循环的情况下有效。

是否可以在一个任务中使用不同的循环,或者必须将其拆分为不同的任务?

- name: "Configure ufw"
      ufw:
        policy: "{{ defaults.policy }}"
        direction: "{{ defaults.direction }}"
        rule: allow
        src: "{{ rules }}"
        logging: on
        state: enabled
      vars:
        defaults:
          - { direction: incoming, policy: deny }
          - { direction: outgoing, policy: allow }
        rules:
          - 80/tcp
          - 443/tcp

运行代码时出现错误

  

“ msg”:“任务包含带有未定义变量的选项。错误是:“列表对象”没有属性“方向”

1 个答案:

答案 0 :(得分:-2)

您需要的是with_nested。这个:

---
- hosts: localhost
  become: no
  connection: local

  vars:
    defaults:
      - { direction: incoming, policy: deny }
      - { direction: outgoing, policy: allow }
    rules:
      - 80/tcp
      - 443/tcp

  tasks:
    - name: Change connect file to bulk mode
      debug:
        msg: "{{ item.0.direction }}: {{ item.1 }}"
      with_nested:
          - "{{ defaults }}"
          - "{{ rules }}"

给出以下输出:

TASK [Change connect file to bulk mode] *********************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": "incoming: 80/tcp"
}
ok: [localhost] => (item=None) => {
    "msg": "incoming: 443/tcp"
}
ok: [localhost] => (item=None) => {
    "msg": "outgoing: 80/tcp"
}
ok: [localhost] => (item=None) => {
    "msg": "outgoing: 443/tcp"
}