I want to access a variable from the "ansible_facts" and get a FAILED with undefined variable


  • name: Testen des lineinfile Modules
    hosts: d127test
    gather_facts: yes
    become: yes

    vars_files:

    tasks:

    • name: Filtern der IP-Adresse von en6
      ansible.builtin.debug:
      msg: “{{ ansible_facts[‘en6’][‘ipv4’][‘address’] }}”
      when: “‘en6’ in ansible_facts”
      register: ip

    • name: Füge Host in /etc/hosts ein
      ansible.builtin.lineinfile:
      path: /etc/hosts
      regexp: “{{ip}}”
      insertafter: ‘[B,b]ackup’
      line: “{{ip}} {{inventory_hostname}}_rub.backup.dc {{inventory_hostname}}_rub”
      state: present
      when: “‘en6’ in ansible_facts”

i become:

fatal: [d127test]: FAILED! => {“msg”: “The task includes an option with an undefined variable. The error was: ‘list object’ has no attribute ‘address’. ‘list object’ has no attribute ‘address’\n\nThe error appears to be in ‘/home/mschm103/ansiblehome/ms_test_rubrik.yml’: line 11, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Filtern der IP-Adresse von en6\n ^ here\n”}

How can I set up the playbook here without losing the formatting?

You didn’t ask a question in your original post, so I’m not sure what you’re looking for here. You are checking

when: "'en6' in ansible_facts"

But are failing on ansible_facts['en6']['ipv4']['address']. The error message says ansible_facts[‘en6’][‘ipv4’] doesn’t contain “address”. Try using debug to print it out and see what it contains and reference accordingly.

For your second post, if you’re asking how to format code in a post, use triple backticks (```) to enclose the code like so:

hello
1
2
3

    - name: Filtern der IP-Adresse von en6
      ansible.builtin.debug:
        msg: "{{ ansible_facts['en6']['ipv4'] }}"
      when: "'en6' in ansible_facts"
      register: ip

Then i become:

    "msg": [
        {
            "address": "100.70.34.119",
            "broadcast": "100.70.63.255",
            "netmask": "255.255.224.0",
            "network": "100.70.32.0"
        }
    ]
}

If I’m reading it right, it looks like ansible_facts['en6']['ipv4'] is actually a list (or array) of dicts, so you’d need to iterate through each entry in a loop or do some kind of fancy json selection thing beyond my skill level (though sometimes AI tools are handy for this).

Something similar to

    - name: Show items in en6
      ansible.builtin.debug:
        msg: "{{ item }}"
      loop: "{{ ansible_facts['en6']['ipv4'] }}"