geerlingguy / geerlingguy/ansible-for-devops
hostvars confusion
- Dominant language
- Python
- Stars
- 9.9k
- Forks
- 3.8k
- PR merge metrics
- No merged PRs in 30d
Description
Hi there,
I have trouble understanding a [paragraph](https://github.com/geerlingguy/ansible-for-devops-manuscript/blob/4f14b52476e60c31c331e0a681db394281e4cde7/chapter5.txt#L456) around page 98 regarding magic variables with host and group variables.
> If you ever need to retrieve a specific host's variables from another host, Ansible provides a magic `hostvars` variable containing all the defined host variables (from inventory files and any discovered YAML files inside `host_vars` directories).
>
> ```yaml
> # From any host, returns "jane".
> {{ hostvars['host1']['admin_user'] }}
> ```
I was wondering how I missed that behavior and did a small test:
```bash
$ tree
.
├── host_vars
│ ├── localhost.yml
│ └── testhost.yml
└── playbook.yml
```
```bash
$ cat playbook.yml
---
- name: Test playbook
hosts: all
tasks:
- name: localhost output
debug:
var: debug_output
- name: testhost output
debug:
var: hostvars['testhost']
$ cat hostvars/localhost.yml
---
debug_output: this comes from the localhost.
$ cat hostvars/testhost.yml
---
debug_output: this comes from the test host.
```
If I run this with the following `ansible-playbook`-command, the variable content for `testhost.yml` is not present.
```
$ ansible-playbook -i localhost, -c local playbook.yml
....
TASK [localhost output] ******************************************************************************************************
lørdag 14 oktober 2023 19:50:20 +0200 (0:00:00.032) 0:00:00.032 ********
lørdag 14 oktober 2023 19:50:20 +0200 (0:00:00.032) 0:00:00.032 ********
ok: [localhost] => {
"debug_output": "this comes from the localhost."
}
TASK [testhost output] *******************************************************************************************************
lørdag 14 oktober 2023 19:50:20 +0200 (0:00:00.025) 0:00:00.058 ********
lørdag 14 oktober 2023 19:50:20 +0200 (0:00:00.025) 0:00:00.057 ********
ok: [localhost] => {
"hostvars['testhost']": "VARIABLE IS NOT DEFINED!"
}
...
Am I misreading this particular paragraph?
Contributor guide
No contributing guide indexed for this repository
Research direction
Read chapter5.txt at line 456, then reproduce the behavior with the shown host_vars files and ansible-playbook command. Compare the documented hostvars example with the inventory used in the reproduction. Done means the paragraph clearly explains the expected hostvars behavior and the conditions illustrated by this example.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- yaml
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100