I have specific variables that need to be applied based on intersections of groups in ansible. For example, if a server is both in prod mode and has the website function, I can specify it in a playbook using tag_function_website:&tag_mode_prod
. This is great, but what do I do if I need to create a group vars file for that intersection that has intersection specific variables (i.e. I don't want to use the same db for dev and prod, but I also have different dbs for boxes of different functions). I can't use an ampersand in a file name, so how do I create a group vars file to specify just the boxes that hit my desired intersection?
The host_vars is a similar folder to group_vars in the repository structure. It contains data models that apply to individual hosts/devices in the hosts. ini file. Hence, there is a YAML file created per device containing specific information about that device.
We can create directories under the group named directory, it will read all the files under these directories in lexicographical. If there is some value which is true for your environment and for every server, the variable containing that value should be defined under /etc/ansible/group_vars/all file.
Ansible treats values of the extra variables as strings. To pass values that are not strings, we need to use JSON format. To pass extra vars in JSON format we need to enclose JSON in quotation marks: ansible-playbook extra_var_json.
With hostvars , you can access variables defined for any host in the play, at any point in a playbook. You can access Ansible facts using the hostvars variable too, but only after you have gathered (or cached) facts.
Maybe I'm not really answering your question, rather sharing some of my experiences with Ansible.
First of all, you should consider having separate inventories for different environments (you've mention dev and prod). I've also started with single inventory initially and I found this advice absolutely astonishing: How to Differentiate Staging vs Production.
The databases that you've used as an example would be probably better referred by separate variable (i.e. hrDb and acctDb).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With