I'm pretty new to Ansible and I'm not sure how to get it right.
To start with, I have implemented this dictionary var for an exemple. There is 2 values but it could be a greater number:
tf_ETCD:
1:
hostname: Etcd01
ip: 192.168.1.141
2:
hostname: Etcd02
ip: 192.168.1.142
I'd like the result to be formatted like that:
{{ tf_ETCD1_Host }}=https://{{ tf_ETCD1_IP }}:2380,{{ tf_ETCD2_Host }}=https://{{ tf_ETCD2_IP }}:2380
So I kinda get it by looping over the list via this code:
- name: Format each value
set_fact:
etcd: "{{ item.value.hostname }}=https://{{ item.value.ip }}:2380,"
loop: "{{ lookup('ansible.builtin.dict', tf_ETCD) }}"
register: etcd_query
- name: Examine the joined string
debug:
msg: "{{ etcd_query['results'][0]['ansible_facts']['etcd'] }}{{ etcd_query['results'][1]['ansible_facts']['etcd'] }}"
The result gave me:
TASK [Format each values] **********************************************************************************************
ok: [] => (item={'key': 1, 'value': {'hostname': 'Etcd01', 'ip': '192.168.1.141'}})
ok: [] => (item={'key': 2, 'value': {'hostname': 'Etcd02', 'ip': '192.168.1.142'}})
TASK [Examine the joined string] ***************************************************************************************
ok: [] => {
"msg": "Etcd01=https://192.168.1.141:2380,Etcd02=https://192.168.1.142:2380,"
}
I cannot figure out how to do a "foreach loop result" in my "Examine the joined string" play.
If you can give me a hint or the concept I'm looking for, you'll save my day.
Figure out how to do a "foreach loop result" in my "Examine the joined string" play ...
A minimal example playbook
---
- hosts: localhost
become: false
gather_facts: false
vars:
tf_ETCD:
1:
hostname: Etcd01
ip: 192.0.2.1
2:
hostname: Etcd02
ip: 192.0.2.2
tasks:
- debug:
msg: "{{ tf_ETCD[ansible_loop.index] }}"
loop: "{{ range(0, tf_ETCD | length, 1) | list }}"
loop_control:
extended: true
- set_fact:
etcd: "{{ etcd | d('') + tf_ETCD[ansible_loop.index].hostname ~ '=https://' ~ tf_ETCD[ansible_loop.index].ip ~ ':2380,' }}"
loop: "{{ range(0, tf_ETCD | length, 1) | list }}"
loop_control:
extended: true
- debug:
msg: "{{ etcd }}"
will result into an output of
TASK [debug] ******************************************************
ok: [localhost] => (item=0) =>
msg:
hostname: Etcd01
ip: 192.0.2.1
ok: [localhost] => (item=1) =>
msg:
hostname: Etcd02
ip: 192.0.2.2
TASK [debug] ******************************************************
ok: [localhost] =>
msg: Etcd01=https://192.0.2.1:2380,Etcd02=https://192.0.2.2:2380,
Some Hints