Vikas Verma
Vikas Verma

Reputation: 313

Ansible: Can we have custom names for host_vars files

What is working

I have ansible inventory organized as below:

../project1
  |- group_vars
  |- host_vars
    |- 10.20.30.1.yml
       {{content like remote-endpoint="x.x.x.x", ... a very big var map... ,}}
    |- 10.20.30.2.yml
       {{content like remote-endpoint="y.y.y.y", ... a very big var map... ,}}
  inventory

content of my inventory file is as below:

10.20.30.1  hvar="host1"
10.20.30.2  hvar="host2"

The above works as expected, I am able to access all the host-level variables for the specific hosts.

What I wanted to do?

I wanted to have names of the host_vars/*files* to be based on the tags (maybe) like - host1, host2, etc instead of the value of "inventory_hostsname" ansible variable. This will enable me to give some function-specific names like master, slave, etc also in the latter case, the names of the files can remain the same even if the host changes.

Upvotes: 0

Views: 1889

Answers (1)

sakibmoon
sakibmoon

Reputation: 2032

Ansible gives the option to give name like you want. Actually that is the preferred way as well. You can define all your hosts in ansible hosts(not /etc/hosts) file like this.

allgrouphost1
allrouphost2

[master]
host1

[slave]
host2
host3
host4

You can then define the variables in host_vars/host1.yml, host_vars/host2.yml and so on.

You can define hosts ip address in hosts file or their specific host vars file with ansible_host variable.

With hosts file

host1 ansible_host=192.0.2.98 ansible_user=deploy

wih host_vars/host1.yml file

ansible_host: 192.0.2.98
ansible_user: deploy

The headings in brackets are group names([master], [slave]), which are used in classifying hosts and deciding what hosts you are controlling at what times and for what purpose.

You can run playbooks by group name so that, those are executed only on those hosts that belongs to that group. You can also define common variables in group_vars file.

See the documentation for more details and use case.

Upvotes: 1

Related Questions