Variable derived from another variable - how to get the result
I am using ansible version 2.7
I have the following vars file v1
envs:
DEV:
D1:
Apps:
App1:
App_name: A1
App2:
App_name: A2
SIT:
S1:
Apps:
App1:
App_name: K1
App1:
App_name: K2
I am passing env_type
as DEV or SIT and env_name
as corresponding D1 or S1.
my command line is
ansible-playbook test.yml -e "env_type='SIT' env_name='S1'"
I am expecting the code to return all the App_name fields for SIT S1 as a list, for further processing.
Can you please suggest how to structure the code.
You could do something like this:
---
- hosts: local
connection: local
gather_facts: no
vars:
envs:
DEV:
D1:
Apps:
App1:
App_name: A1
App2:
App_name: A2
SIT:
S1:
Apps:
App1:
App_name: K1
App2:
App_name: K2
tasks:
- set_fact:
app_list: '{{ envs[env_type][env_name]["Apps"].values() | map(attribute="App_name") | list}}'
Use the values
method of the Apps
object, map
over them to get the attribute App_name
, and then convert the result to a list.
You don't need to use the set_fact
module, but I find it useful when I need to generate facts dynamically.