'Ansible: YAML inventory for staging / production hosts

I can't setup inventory which will be easy and useful in yml format for Ansible Playbook :(

For example:

all:
  children:
    db:
      children:
        production:
          hosts:
            1.1.1.1:

        staging:
          hosts:
            11.11.11.11:

    web:
      children:
        production:
          hosts:
            2.2.2.2:

        staging:
          hosts:
            22.22.22.22:

So, I have two playbooks with:

playbook-db.yml

...
hosts:
  - db

and playbook-web.yml

...
hosts:
  - db

And I want to use this inventory like:

andible-playbook -D playbook-db.yml --limit=staging

I am expecting that my playbook will be used only db and staging hosts, but playbook is applying for all staging hosts: 11.11.11.11 and 22.22.22.22 (but I am expecting 11.11.11.11 only) :(

How I can realize it correctly?



Solution 1:[1]

It seems you have a misunderstanding about the inventory file, since ansible is doing as you described

ansible-inventory -i your-posted-file.yml --list

emits

{   ...
    "all": {
        "children": [
            "db",
            "ungrouped",
            "web"
        ]
    },
    "db": {
        "children": [
            "production",
            "staging"
        ]
    },
    "production": {
        "hosts": [
            "1.1.1.1",
            "2.2.2.2"
        ]
    },
    "staging": {
        "hosts": [
            "11.11.11.11",
            "22.22.22.22"
        ]
    }

showing that the db group has all members of production and staging, but staging has hosts "11.11.11.11", "22.22.22.22" just as you described

I think perhaps you were conflating the yaml indentation with membership, but that's not how ansible inventories work.

What is far more likely is that you'd want a db-staging and db-production group, for the case you described where you want only db hosts that are staging, leaving the db group to mean every db member

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mdaniel