Search code examples
ansibleansible-inventoryhosts

Why, in Ansible, I can't have same key in many children groups?


I want to make some clean stuff with my ansible hosts file.

If i use ansible-playbook --limit calendar -i hosts update_common.yml

Ansible execute my playbook on all hosts, even on hostname in other groups.

Apparently, it seems to comme from my keys dev and prod :

all:
  children:
    gitlab:
      children:
        dev:
          hosts:
            gitlab-dev:  # Stretch
        prod:
          hosts:
            gitlab-A:   # Stretch
            gitlab-B:   # Stretch
            gitlab-C.mysociety.fr:
              ansible_port: 22
    intranet:
      children:
        dev:
          hosts:
            intra-dev:      # Buster
            wordpress-dev:  # Buster
        prod:
          hosts:
            intra-prod:     # Buster
    calendar:
      children:
        dev:
          hosts:
            calendar-dev:
        prod:
          hosts:
            calendar:

Solution

  • Ansible doesn't store the group's tree. The structure is a flat list of all groups. Each group comprises a cumulative list of hosts. If you run the play below

    - hosts: all
      tasks:
        - debug:
            msg: "{{ groups[item] }}"
          loop: "{{ groups.keys()|list }}"
          run_once: true
    

    you'll see that the groups gitlab, intranet, and calendar are identical because they comprise all the hosts from the groups dev and prod. Next, you'll see that the group dev comprises all four hosts, and the group prod comprises all five hosts.

    See Ansible: Intersection of two host groups using yaml inventory.


    Flatten the structure to achieve what you want, e.g.

    all:
      children:
        gitlab_dev:
          hosts:
            gitlab-dev:  # Stretch
        gitlab_prod:
          hosts:
            gitlab-A:   # Stretch
            gitlab-B:   # Stretch
            gitlab-C.mysociety.fr:
              ansible_port: 22
        intranet_dev:
          hosts:
            intra-dev:      # Buster
            wordpress-dev:  # Buster
        intranet_prod:
          hosts:
            intra-prod:     # Buster
        calendar_dev:
          hosts:
            calendar-dev:
        calendar_prod:
          hosts:
            calendar: