Here is a quick sample to show how Ansible can get the value from a dictionary:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
— | |
– hosts: localhost | |
vars: | |
accounts: | |
dev: | |
account: 123 | |
contact: Jackie@123.com | |
uat: | |
account: 456 | |
contact: Jackie@456.com | |
prd: | |
account: 789 | |
contact: Jackie@789.com | |
gather_facts: no | |
tasks: | |
– name: Find account information method 1 | |
debug: | |
msg: "{{ env }} account number is {{ item.value.account }}, contact email is {{ item.value.contact }}" | |
loop: "{{ lookup('dict', accounts) }}" | |
when: "env in item.key" | |
– name: Find account information method 2 | |
debug: | |
msg: "{{ env }} account number is {{ accounts[env].account }}, contact email is {{ accounts[env].contact }}" | |
To test it:
ansible-playbook accounts.yaml -e env=dev
Advertisement
This is the first time I’ve come across this simple construction:
â name: Find account information method 2
debug:
msg: “{{ env }} account number is {{ accounts[env].account }}
Very helpful. Thank you!