My variable file obtained is as below:
cat myvar.yml
dbname: ser1
url_ser1: url1
url_ser2: url2
dbname: ser2
my_ser1_port: 12207
my_ser2_port: 23332
To start off in the first debug, I wish to display the two key (could be more than 2 keys as well) values for dbname
viz ser1
& ser2
I then wish to use the first key's value i.e ser1
to pull all values whose key contains ser1
i.e url1
and 12207
Then ser2
value to get url2
and 23332
Thus, i need the output as below:
The dbname are ser1 & ser2
dbname `ser1` URL is url1 and port is 12207
dbname `ser2` URL is url2 and port is 23332
Below is my playbook however, i got no clue how to read such variable:
---
- name: ReadJsonfile
hosts: localhost
tasks:
- include_vars: myvar.yml
- debug:
msg: "{{ dbname }}"
The above prints only the second dbname value i.e ser2
and not both which is what i require.
- debug:
msg: "{{ '*' item '*' }}"
loop: "{{ dbname }}"
The above fails with error.
Can you please suggest how can i get the desired values of variable's from yaml.
CodePudding user response:
you have to write your myvar.yml like this:
dbname: ['ser1', 'ser2']
url_ser1: url1
url_ser2: url2
my_ser1_port: 12207
my_ser2_port: 23332
so you could loop over dbname...
- name: Reproduce issue
hosts: localhost
gather_facts: no
tasks:
- include_vars: variables.yml
- debug:
msg: "dbname {{ item }} URL is {{ url }} and port is {{ port }}"
loop: "{{ dbname }}"
vars:
port: "{{ lookup('vars', 'my_' item '_port' ) }}"
url: "{{ lookup('vars', 'url_' item) }}"
when: hostvars[ansible_host]['my_' item '_port'] is defined and
hostvars[ansible_host]['url_' item] is defined
so lookup('vars', 'my_' item '_port' )
= hostvars[ansible_host]['my_' item '_port']
result:
ok: [localhost] => (item=ser1) => {
"msg": "dbname ser1 URL is url1 and port is 12207"
}
ok: [localhost] => (item=ser2) => {
"msg": "dbname ser2 URL is url2 and port is 23332"
}