Ansible nested variables

Ansible example which shows how to reach nested variable with dynamic elements.

ansible-nested-variable.yml

# Example which shows how to reach nested ansible variable which is partially different.
# Run that playbook 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 specific CIDRs
      debug:
        msg: "{{ cidr_blocks['vpc_%s_cidr_block' | format(env)] }}" # Be careful about position of square brackets.