Variable in hostvars

Hi all,

I am new to ansible.
Why is my playbook not working?
And how can I solve it?

My playbook:

I am new to ansible.
Why is my playbook not working?

You have a couple of things you need to change.

---
- name: print out ip adressess
   hosts: db_servers
   gather_facts: True
   vars:
     - nic: "enp0s8"
     - full_line: ""

vars is a dict not a list so you need to remove those dashes in front.

   tasks:
   - debug: var=ansible_{{ nic }}.ipv4.address

   - set_fact: full_line="{{ full_line }} {{ hostvars[item].ansible_enp0s8.ipv4.address }}"
     loop: "{{ groups['db_servers'] }}"

   - debug:
       msg: "{{ full_line }}"

   - set_fact: full_line="{{ full_line }} {{ hostvars[item].ansible_{{ nic }}.ipv4.address }}"
     loop: "{{ groups['db_servers'] }}"

You can't use {{ }} inside {{ }}, so you need to concatenate stings to make it work.

{{ hostvars[item]['ansible_' ~ nic].ipv4.address }}

You could drop the loop by using this

- set_fact:
     full_line: "{{ groups['db_servers'] | map('extract', hostvars, ['ansible_' ~ nic, 'ipv4', 'address']) | join(' ') }}"

Hello Kai,

many thnx for the quick respons!
Your solution works fine and it is exactly what I needed.

Happy X-mas to you all.

with regards,

Herman