Ansible/Splitting Hosts File
From charlesreid1
Strategy: create separate variable file for each host and each group
These variable files should be in YAML format
If your playbooks are in playbooks/
, and your hosts file is in playbooks/hosts
, then you would organize the directory as follows:
- put variables for the host
california.example.com
into the fileplaybooks/host_vars/california.example.com
- put variables for the production group in the file
playbooks/group_vars/production
Contents
Examples
Example of flat group variables file
Here is an example of how group variables could be used for a production environment, and all defined in a single file:
group_vars/production
:
db_primary_host: rhodeisland.example.com db_primary_port=5432 db_replica_host: virginia.example.com db_name: widget_production db_user: widgetuser db_password: pFmMxcyD;Fc6)6 rabbitmq_host:pennsylvania.example.com rabbitmq_port=5672
Variables are accessed using the Jinja template variable notation:
{{ db_primary_host }}
Example of YAML group variables file
The group variables file can also be represented with YAML:
group_vars/production
:
db: user: widgetuser password: pFmMxcyD;Fc6)6 name: widget_production primary: host: rhodeisland.example.com port: 5432 replica: host: virginia.example.com port: 5432 rabbitmq: host: pennsylvania.example.com port: 5672
Variables are accessed using nested variable notation:
{{ db.primary.host }}
Further breakdown
You can break it down even further by making production
a directory, and then further group variables into separate files (e.g., one per service).
Rule of thumb: keep it simple. Only use this approach if you really need to.