Ansible, distribute a list to other list

82 Views Asked by At

I'm trying to do this with ansible:

I have multiple "fruits" and want to distrubute to multiple kids:

  - vars:
      kids:
      - John
      - Shara
      - David
      fruits:
      - Banana
      - Mango
      - Orange
      - Peach
      - Pineapple
      - Watermelon
      - Avocado
      - Cherries

Desidered result, something like this:

John:
- Banana
- Peach
- Avocado


Shara:
- Mango
- Pineapple
- Cherries

David:
- Orange
- Watermelon

I tried with zip, zip_longest, list, but no way.

ansible.builtin.debug:
  msg: "{{ item | zip(['a','b','c','d','e','f']) | list }}"
loop:
  - John
  - Shara
  - David
1

There are 1 best solutions below

4
Vladimir Botka On BEST ANSWER

For example

    - set_fact:
        _dict: "{{ dict(kids|zip(_values)) }}"
      vars:
        _batch: "{{ fruits|length|int / kids|length|int }}"
        _values: "{{ fruits|batch(_batch|float|round)|list }}"

gives

  _dict:
    David:
    - Avocado
    - Cherries
    John:
    - Banana
    - Mango
    - Orange
    Shara:
    - Peach
    - Pineapple
    - Watermelon

Q: "Have more than 4 kids"

A: For example

- hosts: localhost
  gather_facts: false
  vars:
    kids:
    - John
    - Shara
    - David
    - Alice
    - Bob
    fruits:
    - Banana
    - Mango
    - Orange
    - Peach
    - Pineapple
    - Watermelon
    - Avocado
    - Cherries
    - Apple
  tasks:
    - set_fact:
        _dict: "{{ dict(kids|zip(_values)) }}"
      vars:
        _batch: "{{ fruits|length|int / kids|length|int }}"
        _values: "{{ fruits|batch(_batch|float|round)|list }}"
    - debug:
        var: _dict

gives

  _dict:
    Alice:
    - Avocado
    - Cherries
    Bob:
    - Apple
    David:
    - Pineapple
    - Watermelon
    John:
    - Banana
    - Mango
    Shara:
    - Orange
    - Peach