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

后端 未结 7 759
执笔经年
执笔经年 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:35

    Well, you cannot directly build an array, but you can achieve the same effort with a dict.

    Suppose you want to construct an array:

    [{
        name: 'bob',
        age: 30
    }, {
        name: 'alice',
        age: 35 
    }]
    

    You can put each element in a file like:

    bob.yml

    bob:
      name: bob
      age: 30
    

    alice.yml

    alice:
      name: alice
      age: 35
    

    Place these files in the same dir (e.g. user), then use include_vars to load the whole dir:

    - name: Include vars
      include_vars:
        name: users
        dir: user
    

    This will give you a dict users:

    users:
      alice:
        name: alice
        age: 35
      bob:
        name: bob
        age: 30
    

    User the dict2items filter in ansible, you get the array you want

提交回复
热议问题