How to loop over a host group in ansible providing a dynamic value

Viewed 1484

I have the following inventory

group1:
  host001:
  host002:
group2:
  host101:
  host102:

Now I want to loop over either of the groups, controlled via a parameter e.g.

- hosts: localhost
  vars:
    target: group1
- name: Do something for an inventory group
  include_tasks: sample-play.yml
  loop: "{{ groups['{{ target }}'] }}"

Is that even possible? if yes how? I tried

loop: "{{ groups['{{ target }}'] }}"

and

loop: "{{ groups.{{ target }} }}"

Both ending with the following error:

fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ groups.{{ target }} }}"}

What I want to achieve is to modify a local file and add an entry for each host in a group. Concretely I want to add a proxy entry for each host of a group to the ssh config-file.

2 Answers

Fix the syntax

loop: "{{ groups[target] }}"

Expansion can't be nested "{{ {{ }} }}".

By default Ansible forks the play for a given host group (controlled by ansible.cfg). Looks like you want to execute tasks sequentially as if iterating over the group.

There are many ways to control playbook execution.

You can use the serial keyword as below if you want run the tasks on hosts in your group sequentially:

- hosts: group1
  serial: 1

  tasks:
  - name: Do something for an inventory group
    include_tasks: sample-play.yml

This will make Ansible run sample-play.yml for host001 first, then rerun on host002

Related