Ansible: overriding dictionary variables in extra-

2019-01-26 18:03发布

问题:

This question already has an answer here:

  • Ansible. override single dictionary key [duplicate] 4 answers

In my Ansible playbook I have a nested variable declaration as shown below in a variable file.

repo:
  branch: int
  url: git@github:user/repo.git
  dest: "/var/code"

How would I override the branch param in extra-vars? I tried something like this below but it didn't work.

 --extra-vars "repo.branch=exec_refactor"

neither this

 --extra-vars "repo[branch]=exec_refactor"

using JSON representation like below results in overriding the entire repo node and hence repo.branch is successfully overridden but both repo.url and repo.dest becomes undefined.

 --extra-vars '{"repo":{"branch":"exec_refactor"}}'

回答1:

To merge dicts, you need to set hash_behaviour=merge in your ansible.cfg. But it is not recommended to do this since pretty much all roles you find on Ansible Galaxy do expect the default value replace and might run crazy.

See hash_behaviour in the docs.

I once had a similar problem and wrote an action plugin to solve it: include_vars_merged. It is no out-of-the-box solution for your problem because Ansible in any case will override the dict with the one from --extra-vars and using my plugin, you would again override that single value you passed in --extra-vars. But it should not be too hard to modify the plugin and only add new values instead of overriding values. I think switching parameters in line 34 & 40 in include_vars_merged.py should already do it.