In Ansible, how to combine variables from separate files into one array?

后端 未结 7 728
执笔经年
执笔经年 2020-12-03 21:27

In Ansible, in a role, I have vars files like this:

vars/
    app1.yml
    app2.yml

Each file contains vars specific to an app/website like

相关标签:
7条回答
  • 2020-12-03 21:57

    You can not do that. Variables will always override variables with the same name. The only thing you could do with this exact setup is to write your own vars plugin which reads those files and merges them into an array.

    If you are open to change the structure of your apps definition you can use a hash and set your hash_behavior=merge. In each vars file then you'd have a definition like:

    apps:
      app1:
        git_repo: https://github.com/philgyford/app1.git
    

    apps:
      app2:
        git_repo: https://github.com/philgyford/app2.git
    

    When Ansible loads both files it will merge it automatically together into:

    apps:
      app1:
        git_repo: https://github.com/philgyford/app1.git
      app2:
        git_repo: https://github.com/philgyford/app2.git</pre>
    

    But be advised that hash_behavior=merge fundamentally changes the default behavior of Ansible on a global level. Make sure all your roles do not have issues with this setting. The documentation mentions:

    We generally recommend not using this setting unless you think you have an absolute need for it

    If you still use Ansible 1 you could use one of my old plugins instead: include_vars_merged. Basically this adds the behavior of hash_behavior=merge to only a single task.

    I have not yet looked into migrating this to Ansible 2 though and currently it looks like I won't have the need for it any longer.

    0 讨论(0)
提交回复
热议问题