Ansible nested loops through inventories plus oute

2019-07-27 18:40发布

问题:

Suppose I have the following playbook:

---
- hosts: all
  gather_facts: False
  vars:
    group: 'dev'

  tasks:
  - name: Just loop through a group and group_vars
    debug:
      msg: 'group is {{group}} target is {{item.0}} port is {{item.1}}'
    loop: >
      {{ groups[group] |
         product(hostvars[groups[group][0]]["ports"]) |
         list }}

How can I change the loop part in case I have the variable named "group" defined as list and not as a single variable? For example:

vars:
  group:
  - 'dev'
  - 'int'

Thanks and regards.

Stef

回答1:

loop: >
   {{ groups | dict2items | 
      selectattr("key", "in", group_list ) |
      map(attribute="value") | list |
      ### and then the rest of your pipeline }}

I think will do what you want