Ansible loop using multi-ter group_vars

2019-06-04 08:18发布

问题:

I'm trying to dynamically create templates in ansible using group_vars but cannot seem to get the nested loop working.

In group_vars, I have

my_environment:
  serv1:
    foo: 2
    bar: 3
    baz: 3
  serv2:
    foo: 1

I'm trying to create the following structure:

/serv1/foo1
/serv1/foo2

/serv1/bar1
/serv1/bar2
/serv1/bar3

/serv1/baz1
/serv1/baz2
/serv1/baz3

/serv2/foo1

Once the above is created, I want to put a template file into each directory so the final result would be:

/serv1/bar1/template

and

/serv2/foo1/template

etc.

My playbook:

- debug: msg="{{ ce }}"
  with_list:
    - "{{ item.value }}"
  loop_control:
    loop_var: ce

The above outputs:

ok: [localhost] => (item=None) => {
    "ce": {
        "bar": 3,
        "baz": 3,
        "foo": 2
    },
    "msg": {
        "bar": 3,
        "baz": 3,
        "foo": 2
    }
}

The question is, how do I use the value of foo to iterate 2 times to create the structure? Whenever I use an include: with_dict or include: with_list I keep on just getting the above list? I can't find a way to traverse down...

回答1:

The best way is to write your own lookup plugin that will form the desired list of paths from your input.

Using standard lookups(loops) you can do it this way:
x.yml:

- hosts: localhost
  vars:
    my_environment:
      serv1:
        foo: 2
        bar: 3
        baz: 3
      serv2:
        foo: 1
  tasks:
    - include: x2.yml
      with_dict: "{{ my_environment }}"
      loop_control:
        loop_var: my_server

x2.yml:

- include: x3.yml
  with_dict: "{{ my_server.value }}"
  loop_control:
    loop_var: my_param

x3.yml:

- debug: var=item
  with_sequence: end={{ my_param.value }} format=/{{ my_server.key }}/{{ my_param.key }}%1d/template

debug in x3.yml you can replace with template and use {{ item }} as dest.