Last active
June 10, 2016 11:49
-
-
Save smaeda-ks/1be9ab6401b3448c39bf62d2850c7546 to your computer and use it in GitHub Desktop.
Ansible filter plugin
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
$ 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 |
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
# 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} |
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 | |
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