Reputation: 1652
I have vars where I put something like this:
vars/main.yml
hello_port: 80
world_port: 81
in my ansbile file I load the vars with
vars_files:
- ./vars/main.yml
This is how I initialize m_name:
- name: set_fact
set_fact:
m_name:
- 'hello'
- 'world'
and after that I have task with iterate using with_items:
- debug:
msg: "{{ (item + '_port') }}"
with_items: "{{ m_name }}"
But I've got as output
hello_port
world_port
not their values.
OK I find that if I use debug var it is working. But If I want to put this expression "{{ (item + '_port') }}"
for an example in shell task it does not evaluate it. Is there a way to evaluate the dynamically created variables name - to get the value?
Upvotes: 18
Views: 53978
Reputation: 687
https://docs.ansible.com/ansible/2.5/plugins/lookup/vars.html
- name: Show value of 'variablename'
debug:
msg: "{{ lookup('vars', 'variabl' + myvar)}}"
vars:
variablename: hello
myvar: ename
Upvotes: 34
Reputation: 33
I guess best way is to use varnames_lookup
- name: List variables that start with qz_
debug: msg="{{ lookup('varnames', '^qz_.+')}}"
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/varnames_lookup.html
Upvotes: 1
Reputation: 659
{{ hostvars[inventory_hostname][item + '_port'] }}
http://docs.ansible.com/ansible/latest/faq.html#how-do-i-access-a-variable-name-programmatically
Upvotes: 9