0

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'"
New contributor
Fraeco is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
0

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

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"
}
New contributor
Fraeco is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • @Freco: I posted msg: "{{ hostvars[item].ipv4 }}". It's wrong syntax var: "{{ hostvars[item].ipv4 }}", because "{{ hostvars[item].ipv4 }}" isn't a variable. It's string. This is also the reason for "Ansible is still barking at me saying my variable isn't defined". – Vladimir Botka Jun 12 at 16:51

Your Answer

Fraeco is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.