Skip to content

Instantly share code, notes, and snippets.

@smaeda-ks
Last active June 10, 2016 11:49
Show Gist options
  • Save smaeda-ks/1be9ab6401b3448c39bf62d2850c7546 to your computer and use it in GitHub Desktop.
Save smaeda-ks/1be9ab6401b3448c39bf62d2850c7546 to your computer and use it in GitHub Desktop.
Ansible filter plugin
$ ansible-playbook -i localhost, hoge.yml
PLAY [localhost] **************************************************************
TASK: [debug ] ****************************************************************
ok: [localhost] => {
"var": {
"dict_merged": {
"foo": {
"bar": 1,
"baz": 2
},
"qux": 2
}
}
}
TASK: [debug ] ****************************************************************
ok: [localhost] => {
"var": {
"dict_update": {
"foo": {
"baz": 2
},
"qux": 2
}
}
}
PLAY RECAP ********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
# idea from here
# https://www.xormedia.com/recursively-merge-dictionaries-in-python/
from copy import deepcopy
def dict_merge(a, b):
if not isinstance(b, dict):
return b
result = deepcopy(a)
for k, v in b.iteritems():
if k in result and isinstance(result[k], dict):
result[k] = dict_merge(result[k], v)
else:
result[k] = deepcopy(v)
return result
class FilterModule(object):
def filters(self):
return {'dict_merge': dict_merge}
- hosts: localhost
gather_facts: no
vars:
dict:
foo:
bar: 1
dict2:
foo:
baz: 2
qux: 2
# custom filter plugin
dict_merged: "{{ dict | dict_merge(dict2) }}"
# jinja2 default update
dict_update: |
{% do dict.update(dict2) %}
{{ dict }}
tasks:
- debug:
var: dict_merged
- debug:
var: dict_update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment