Skip to content

Instantly share code, notes, and snippets.

@enisozgen
Last active November 4, 2023 10:21
Show Gist options
  • Save enisozgen/28664601d54dd057403a9f82829787d6 to your computer and use it in GitHub Desktop.
Save enisozgen/28664601d54dd057403a9f82829787d6 to your computer and use it in GitHub Desktop.
Ansible example which shows how to reach nested variable with dynamic elements
# Example which shows how to reach nested ansible variable which is partially different.
# Run that plabook with ansible-playbook -e "env=test" ansible-nested-variable.yml
---
#
- hosts: localhost
connection : ssh
gather_facts: no
vars:
cidr_blocks:
vpc_production_cidr_block: "10.10.0.0/28"
vpc_infra_cidr_block: "10.20.0.0/28"
vpc_test_cidr_block: "10.30.0.0/28"
tasks:
- name: Show all CIDRs
debug:
msg: "{{ cidr_blocks}}"
- name: Show spesific CIDRs
debug:
msg: "{{ cidr_blocks['vpc_%s_cidr_block' | format(env)] }}" # Be careful about position of square brackets.
@flannon
Copy link

flannon commented May 24, 2021

Nicely done! Thanks for sharing.

@metajiji
Copy link

metajiji commented Jun 28, 2021

If use python string function format() instead jinja filter, we dont need be careful with position of square brackets.
msg: "{{ cidr_blocks['vpc_{env}_cidr_block'.format(env=env)] }}"

@enisozgen
Copy link
Author

If use python string function format() instead jinja filter, we dont need be careful with position of square brackets.
msg: "{{ cidr_blocks['vpc_{env_cidr_block'.format(env=env)] }}"

Good to know thanks @metajiji

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment