Skip to content

Instantly share code, notes, and snippets.

@miticojo
Last active April 30, 2018 10:41
Show Gist options
  • Save miticojo/886e8eb6f52cec290a65ccaba294802f to your computer and use it in GitHub Desktop.
Save miticojo/886e8eb6f52cec290a65ccaba294802f to your computer and use it in GitHub Desktop.
Ansible loop and dict combine
- hosts: localhost
gather_facts: no
vars:
# structure from https://docs.ansible.com/ansible/2.5/plugins/inventory/yaml.html
inventory:
all: # keys must be unique, i.e. only one 'hosts' per group
hosts:
test1:
test2:
var1: value1
vars:
group_var1: value2
children: # key order does not matter, indentation does
other_group:
children:
group_x:
hosts:
test5
vars:
g2_var2: value3
hosts:
test4:
ansible_host: 127.0.0.1
last_group:
hosts:
test1 # same host as above, additional group membership
vars:
last_var: MYVALUE
tasks:
- include_tasks: var_item.yml
vars:
chiave: "{{item.0}}"
valore: "{{item.1}}"
loop_control:
loop_var: "item"
with_together:
- ['a', 'b', 'c']
- [111, 222, 333]
- debug:
var: hosts
- set_fact:
inventory: "{{ inventory | combine({'all': {'hosts': hosts}}, recursive=True) }}"
- debug:
var: inventory
- copy:
content: "{{inventory|to_nice_yaml}}"
dest: ./inventory
- set_fact:
hosts: "{{ hosts | default({}) | combine({chiave: valore}) }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment