Skip to content

Instantly share code, notes, and snippets.

@halberom
Last active November 8, 2017 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halberom/286459c63180076dff0f1ef208106ecf to your computer and use it in GitHub Desktop.
Save halberom/286459c63180076dff0f1ef208106ecf to your computer and use it in GitHub Desktop.
ansible - example of different ways of getting elements from a list of dicts or nested dict structure
---
- hosts: localhost
gather_facts: False
connection: local
vars:
networks:
- { name: "public", type: public }
- { name: "private", type: private }
- { name: "prod-cluster", cidr: "192.172.0.0/24", reverse: "0.172.192.in-addr.arpa", type: cluster }
alternative:
public:
- { name: "public" }
private:
- { name: "private" }
cluster:
- { name: "prod-cluster", cidr: "192.172.0.0/24", reverse: "0.172.192.in-addr.arpa" }
selection:
- public
- cluster
- private
tasks:
- set_fact:
networks_in_selection: "{{ networks_in_selection|default([]) + [item] }}"
when: item.type in selection
with_items: "{{ networks }}"
# which when Jinja 2.10 is out (http://jinja.pocoo.org/docs/dev/templates/#in) could be rewritten as
- set_fact:
networks_in_selection: "{{ networks|selectattr('type', 'in', selection)|list }}"
- set_fact:
networks_in_selection: "{{ networks_in_selection|default([]) + [item.value] }}"
when: item.key in selection
with_dict: "{{ alternative }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment