Darwick
Darwick

Reputation: 350

Ansible loop in items and then loop again with a module (nested loop)

I have a list of items in my playbook.

x_ssl_certs:
  - 'host1.domain.tld'
  - 'host2.domain.tld'
  - 'host3.domain.tld'
  - 'anotherhost.domain.tld'

Each of it has it's own SSL files, like host1.domain.tld.key host1.domain.tld.crt host1.domain.tld.fullchain ... and so on. Now I using this playbook to send out this files:

- name: Copy the {{ item }} key files
  copy:
    src: "{{ item }}/{{ item }}.key"
    dest: '/etc/ssl/{{ item }}.key'
    owner: 'root'
    group: 'root'
    mode: '0644'
  loop: "{{ x_ssl_certs }}"

- name: Copy the {{ item }} crt files
  copy:
    src: "{{ item }}/{{ item }}.crt"
    dest: '/etc/ssl/{{ item }}.crt'
    owner: 'root'
    group: 'root'
    mode: '0644'
  loop: "{{ x_ssl_certs }}"

- name: Copy the {{ item }} fullchain files
  copy:
    src: "{{ item }}/{{ item }}.fullchain"
    dest: '/etc/ssl/{{ item }}.fullchain'
    owner: 'root'
    group: 'root'
    mode: '0644'
  loop: "{{ x_ssl_certs }}"

and so on, 1 task for every file. I would like to integrate this into one or two task, so it should lookup the x_ssl_certs list and send out each file which belongs to them. This files are the same naming convention for each item in the list.

This should be a loop in the loop, nested loop, or something like that, but based on the documentation it is not exactly clear for me how to make that.

Upvotes: 1

Views: 305

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68189

Use with_nested. For example,

    - debug:
        msg: "Copy {{ item.0 }}.{{ item.1 }}"
      with_nested:
        - "{{ x_ssl_certs }}"
        - [key, crt, fullchain]

gives

  msg: Copy host1.domain.tld.key
  msg: Copy host1.domain.tld.crt
  msg: Copy host1.domain.tld.fullchain
  msg: Copy host2.domain.tld.key
  msg: Copy host2.domain.tld.crt
  msg: Copy host2.domain.tld.fullchain
  msg: Copy host3.domain.tld.key
  msg: Copy host3.domain.tld.crt
  msg: Copy host3.domain.tld.fullchain
  msg: Copy anotherhost.domain.tld.key
  msg: Copy anotherhost.domain.tld.crt
  msg: Copy anotherhost.domain.tld.fullchain

Upvotes: 3

Related Questions