Ansible example – get dictionary value


Here is a quick sample to show how Ansible can get the value from a dictionary:

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 }}"
view raw accounts.yaml hosted with ❤ by GitHub

To test it:

ansible-playbook accounts.yaml -e env=dev

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s