Search code examples
ansibleansible-inventory

Use host variables in ansible playbook


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'"

Solution

  • 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)