Ansible: how to construct a variable from another variable and then fetch it's value
If you have a variable like
vars:
myvar: xxx
xxx_var: anothervalue
the working Ansible syntax:
- debug: msg={{ vars[myvar + '_var'] }}
will give you the analogue of:
- debug: msg={{ xxx_var }}
You can use "hostvars" to pass the variable, host facts can be loaded from group vars or host vars
yml
---
- name: "Play to for dynamic groups"
hosts: x0
vars:
- target_host: smtp
tasks:
- set_fact: smtp_host="smtp.max.com"
- set_fact: host_var_name={{target_host}}_host
- set_fact: dym_target_host={{hostvars[inventory_hostname][host_var_name]}}
- name: testing
debug: msg={{ target_host }}
- name: testing
debug: msg={{ smtp_host }}
- name: testing
debug: msg={{ target_host }}_host
- name: testing
debug: msg={{ dym_target_host }}
output:
PLAY [Play to for dynamic groups] *********************************************
GATHERING FACTS ***************************************************************
ok: [x0]
TASK: [set_fact smtp_host="smtp.max.com"] *************************************
ok: [x0]
TASK: [set_fact host_var_name=smtp_host] **************************************
ok: [x0]
TASK: [set_fact dym_target_host={{hostvars[inventory_hostname][host_var_name]}}] ***
ok: [x0]
TASK: [testing] ***************************************************************
ok: [x0] => {
"msg": "smtp"
}
TASK: [testing] ***************************************************************
ok: [x0] => {
"msg": "smtp.max.com"
}
TASK: [testing] ***************************************************************
ok: [x0] => {
"msg": "smtp_host"
}
TASK: [testing] ***************************************************************
ok: [x0] => {
"msg": "smtp.max.com"
}
PLAY RECAP ********************************************************************
x0 : ok=8 changed=0 unreachable=0 failed=0
This is possible as of Ansible 2.5 with the vars
lookup plugin, which I think is less likely to break without warning than some of the other methods posted here. For example:
---
- name: "Example of dynamic groups"
hosts: localhost
vars:
- target_host: smtp
- smtp_host: smtp.max.com
tasks:
- name: testing
debug: msg={{ lookup('vars', target_host + '_host') }}
Output:
PLAY [Example of dynamic groups] **************************************************
TASK [Gathering Facts] **************************************************
ok: [localhost]
TASK [testing] **************************************************
ok: [localhost] => {
"msg": "smtp.max.com"
}