How to iterate over nested list and split it into two groups using add_host?

Hey,

Given the following playbook -

  • hosts: localhost
    gather_facts: false
    vars:
    my_hosts:

  • [‘host1’, ‘host2’]

  • [‘host3’]

  • name: Add host
    add_host:
    name: ‘{{ item }}’
    groups: “group{{ index }}”
    loop: “{{ my_hosts }}”
    loop_control:
    index_var: index

Flatten the lists.

      loop: "{{ my_hosts|flatten }}"

Cheers,

  -vlado

Thanks for the hint,

Flatting the list results with

`

TASK [print] ********************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
“msg”: {
“all”: [
“host1”,
“host2”,
“host3”
],
“group0”: [
“host1”
],
“group1”: [
“host2”
],
“group2”: [
“host3”
],
“ungrouped”:
}
}

`

What i’m trying to achieve is -

`

TASK [print] ********************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
“msg”: {
“all”: [
“host1”,
“host2”,
“host3”
],
“group0”: [
“host1”,
“host2”
],
“group1”: [
“host3”
],
“ungrouped”:
}
}

`

You've said "I want this to be dynamic as much as possible". Where does this
"dynamic" assignment of the hosts to the groups come from? Any structure? If
not it might be hard-coded i.e not dynamic at all. Make your choice.

Cheers,

  -vlado

If the hosts from 1st element of the list come to group0, from 2nd to
group1 and so on ... The play below

  vars:
    my_hosts:
      - ['host1', 'host2']
      - ['host3']
  tasks:
    - include_tasks: loop.yml
      loop: '{{ my_hosts }}'
      loop_control:
        loop_var: outer_item
        index_var: outer_idx
    - debug:
        var: groups

with this included task below gives the groups.

  $ cat loop.yml
  - add_host:
      name: "{{ item }}"
      groups: "{{ 'group' ~ outer_idx }}"
    loop: "{{ outer_item }}"

Cheers,

  -vlado