How to use host_vars in Ansible?

Viewed 1997

I created a variable in group_vars

group_vars/all

---
hostname: name1

I want to set name2 to the real host(10.20.30.40), so I created a file and set the hostname again there

host_vars/10.20.30.40

---
hostname: name2

When I run the playbook, it returned name1 but not name2:

roles/os/tasks/main.yml

- name: Print hostname
  ansible.builtin.debug:
    msg: "{{ hostname }}"

Result:

TASK [server : Print hostname] *************************************
ok: [web_server] => {
    "msg": "name1"
}

I want to set the variable in each host that I want to update, isn't it the right usage?


And, if I name the host file this way under the host_vars folder, does it work?

web_server

The inventory:

[web_server]
10.20.30.40

playbook:

---
- hosts: web_server
  become: true
  vars_files:
    - group_vars/all
  roles:
    - os
1 Answers

Q: "When I run the playbook, it returned name1 but not name2."

shell> cat hosts
[web_server]
10.20.30.40
shell> cat group_vars/all
---
hostname: name1
shell> cat host_vars/10.20.30.40 
---
hostname: name2
shell> cat playbook.yml
---
- hosts: web_server
  vars_files:
    - group_vars/all
  tasks:
    - debug:
        var: hostname

A: Don't include group_vars/all in a playbook.

The playbook's group_vars/all are included by the playbook automatically at precedence 5. See Understanding variable precedence. If you put group_vars/all into the vars_files (precedence 14) you override the host_vars (precedence 10).


Example. Given the inventory

shell> cat hosts
[web_server]
10.20.30.40
10.20.30.41

the playbook

shell> cat playbook.yml
---
- hosts: web_server
  gather_facts: false
  tasks:
    - debug:
        var: hostname

gives as expected

shell> ansible-playbook -i hosts playbook.yml 

PLAY [web_server] *********************************************************

TASK [debug] **************************************************************
ok: [10.20.30.40] => 
  hostname: name2
ok: [10.20.30.41] => 
  hostname: name1

The variable in host_vars/10.20.30.40 override the variable in group_vars/all

Related