0
votes

I'm trying to reference host variables in a playbook in combination with "with_items".

My inventory

[container]
testcontainer-01.example.org template_name="syslog" ipv4="192.168.1.101"
testcontainer-02.example.org template_name="syslog" ipv4="192.168.1.102"

The playbook:

  tasks:
    - debug:
        var: "{{ item.ipv4 }}"
      with_items:
        - "{{ groups['container'] }}"

Whenever I run the play I get the following error:

The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'ipv4'

When I ask debug for just {{ item }},without the ipv4 attribute it just says the variable isn't defined.

"testcontainer-01.example.org ": "VARIABLE IS NOT DEFINED!: Unable to look up a name or access an attribute in template string ({{testcontainer-01.example.org}}).\nMake sure your variable name does not contain invalid characters like '-': unsupported operand type(s) for -: 'StrictUndefined' and 'StrictUndefined'"
2

2 Answers

0
votes

If you want ipv4 of the host running the play use

- debug:
    var: ipv4

If you want to list all ipv4 in container use

- debug:
    msg: "{{ hostvars[item].ipv4 }}"
  loop: "{{ groups['container'] }}"

(not tested)

-1
votes

As posted by Vladimer Botka, the following works.

- debug:
        var: "{{ hostvars[item].ipv4 }}"
      with_inventory_hostnames:
        - container

For some reason Ansible is still barking at me saying my variable isn't defined. None the less it yields the result that I need. The value of the ipv4 variable is being used in the correct places.

ok: [containerhost.example.org] => (item=testcontainer-02.example.org) => {
    "192.168.1.102": "VARIABLE IS NOT DEFINED!", 
    "item": "testcontainer-02.example.org"
}
ok: [containerhost.example.org] => (item=testcontainer-01.example.org) => {
    "192.168.1.101": "VARIABLE IS NOT DEFINED!", 
    "item": "testcontainer-01.example.org"
}