Defining host as variable in Ansible hosts file

2020-08-01 07:13发布

问题:

I have a rather simple hosts file

[clients]
qas0062
[dbs_server]
qas0063

For the users of the project we don't want them to modify hosts file but rather we have a separate user.config.yml file that contain various user-configurable parameters. There we have entry such as

dbs_server: qas0065

So the question is: is it possible to use a variable in the hosts file that would use a value defined in user.config.yml? And what would be the format?

回答1:

Pretty sure you can't templatize the actual host key entry in the inventory, but you can templatize the value of its ansible_host connection var to achieve roughly the same effect, eg:

[clients]
clienthost ansible_host="{{ clienthost_var }}"
[dbs_server]
dbsserver ansible_host="{{ dbsserver_var }}"

then set the value of those vars from external vars before the play starts executing (eg, with the vars_files directive or -e).



回答2:

There is another way to do the same thing. We can simply refer to values in the hosts (inventory) file by using the following syntax in our playbook

host={{ groups['dbs_server'][0] }}

This works well when you have one entry in the group (db_server in this specific case)