Ansible issues extracting a value from host vars

Viewed 36

I am looking at extracting the value of Ansible host from hostvars, however I am not just getting the value.

the purpose is to select a random host from a group and use the name and IP to create a VM instance on proxmox as a sudo load balanced way of creating VMs.

Here is my playbook:

---
- hosts: localhost
  become: yes
  vars:
    - testvar: "{{ groups['proxmox_hypervisor'] | random }}"
    - anothertest: "hostvars.{{ testvar }}.ansible_host"
  tasks:
   - name: Print Host IP Address
     ansible.builtin.debug:
        var: "{{ anothertest }}"

I'm getting

TASK [Print Host IP Address] ******************************************
task path: /home/ansible/ceh-ansible/test.yml:8
ok: [localhost] => {
    "hostvars.b550.ansible_host": "192.168.5.178"
}

but I'm expecting

TASK [Print Host IP Address] *******************************************
task path: /home/ansible/ceh-ansible/test.yml:8
ok: [localhost] => {
    "192.168.5.178"
}

What am I doing wrong?

2 Answers

You probably have a misconception of YAML to start with:

vars:
  - testvar: "{{ groups['proxmox_hypervisor'] | random }}"
  - anothertest: "hostvars.{{ testvar }}.ansible_host"

Is creating a list of dictionaries

my_var:
  - testvar: b550
  - anothertest: hostvars.b550.ansible_host

This will force you to access elements in a complicated way:

  • my_var.0.testvar
  • my_var.1.anothertest

While, what you probably want in your variables is a dictionary:

my_var:
  testvar: b550
  anothertest: hostvars.b550.ansible_host

Then, you are not templating your anothertest variable, so, it should rather be:

testvar: "{{ groups['proxmox_hypervisor'] | random }}"
anothertest: "{{ hostvars[testvar].ansible_host }}"

All this said, there is a way easier manner to achieve this, use the randomness as your hosts parameter:

- hosts: "{{ groups['proxmox_hypervisor'] | random }}"
  gather_facts: no  

  tasks:
   - name: Print host IP address
     ansible.builtin.debug:
       var: "{{ ansible_host }}"

You may have a look into the following example

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    b550:
      ansible_host: "192.168.5.178"

  tasks:

  - name: Debug var
    debug:
      var: b550.ansible_host

  - name: Debug msg
    debug:
      msg: "{{ b550.ansible_host }}"

resulting into an output of

TASK [Debug var] *****************
ok: [localhost] =>
  b550.ansible_host: 192.168.5.178

TASK [Debug msg] *****************
ok: [localhost] =>
  msg: 192.168.5.178

Further Documentation

Related