Search code examples
ansibleansible-inventory

Ansible common variables for multiple inventories


I would like to define a set of variables that must be inherited by any inventory I will use with playbooks. At the moment I have the following folder structure:

inventory/
  inv1.yml
  inv2.yml
playbooks/
  group_vars/
    all.yml
    inv1.yml
    inv2.yml
  play1.yml
  play2.yml

This structure allows me to inherit from all.yml the common variables, but if I need to override some of them I need to create a custom group_vars file: I read the variable precedence rules and understood that this is the expected behavior.

I would like to know if I can change something in my file organization to override common variables with definitions in inventory files. This would allow me to avoid splitting common overrides in a separate file and specific variables in inventory.


Solution

  • I found myself a solution (probably better say hack) that fits my requirements based on multi inventory support: I replaced playbooks/group_vars/all.yml with a fake inventory called inventory/all.yml that only contains host group all and defines default values for variables (no hosts are in this inventory).

    Then I run the playbook with command:

    $ ansible-playbook playbooks/play1.yml -i inventory/all.yml -i inventory/inv1.yml
    

    This way I can override variables defined in inventory/all.yml with the ones in inventory/inv1.yml.

    I am not 100% happy with this solution because it forces me to explicitly define in command line 2 inventories, so I sign this as the accepted answer but I wiil keep looking for improvements.