Hi Christoph, I tried this with one of my Ansible work, looks like it does not work well if we have a nested dict. any suggestions ?
On Saturday, 4 May 2019 at 14:34:18 UTC+5:30 Max Bigras wrote: > Hi christoph, > > Was very excited to see your solution to this problem. > I've been struggling to find a way to work around ansible replacing > dictionaries. > > Are you still using this approach? > How has it been working for you? > Have you made any changes? > > On Wednesday, June 6, 2018 at 7:00:46 AM UTC-7, > [email protected] wrote: >> >> Hi Kai, >> >> >>> Ansible has an option hash_behavior(default is replace) that you can set >>> to merge, it will then merge hashes/dictonaries instead of replacing >>> them. >>> >> >> Unfortunately, DEFAULT_HASH_BEHAVIOUR (Ansible Docs) >> <http://docs.ansible.com/ansible/latest/reference_appendices/config.html?highlight=hash_behaviour#default-hash-behaviour> >> >> states that it is not a recommended practice. But luckely, I found a way >> that seems to be pretty straight-forward: >> >> role/default/main.yml >> myapp_defaults: >> component1: >> feature1: defaultA >> feature2: defaultB >> component2: >> feature1: defaultC >> feature2: defaultD >> >> role/vars/main.yml >> myapp_vars: | >> {%- if myapp is defined and myapp is iterable -%} >> {{ myapp_defaults | combine (myapp, recursive=True) }} >> {%- else -%} >> {{ myapp_defaults }} >> {%- endif -%} >> >> The usage in the role/tasks/xyz.yml then is e.g. >> - name: Some task >> XXX: >> YYY: "{{ myapp_vars.component2.feature1 }}" >> ... >> ... >> >> Applying the role e.g. with play vars >> # My Playbook >> >> - name: setup MyApp >> vars: >> myapp: >> component2: >> feature1: "foo" >> feature2: "bar" >> tasks: >> - include_role: >> name: myapp >> >> Variable precedence is important, e.g. the following wouldn't work: >> # My Playbook >> >> - name: setup MyApp >> tasks: >> - include_role: >> name: myapp >> vars: >> myapp: >> component2: ... >> ... >> >> since role/vars/main.yml is already read in when include_vars are >> applied. >> >> >> >> >> >> -- You received this message because you are subscribed to the Google Groups "Ansible Project" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/efdad727-7aa3-4550-8f06-da83562a5bbfn%40googlegroups.com.
