Use two with_items loops in one Task

Asked by At

I did quite some research on this question. Though i did not find the answer to solve my problem.

I want to delete a directorys content with ansibe with deleting the directory itself. I want to do this for multiple directorys.

In theory i want to do something like this:

- name: Delete dir on Prod/Stag
  file:
    state: "{{ item.1 }}"
    path: "{{ /path/ }}{{ item.2 }}/"
  with_items.1:
    - absent
    - directory
  with_items.2:
    - test1
    - test2
    - test3
    - test4

Sadly this does not work. This is what i have right now.

- name: Delete dir
  file:
    state: absent
    path: "{{ path }}{{ item }}/"
  with_items:
    - test1
    - test2
    - test3
    - test4

Is there a way to make this code shorter by creating two loops?

1 Answers

1
Jack On

You want with_nested:

  - debug:
      msg: "state: {{ item.0 }}; path: {{ item.1 }}"
    with_nested:
      - [ absent, directory ]
      - [ sys, wifi, reco-properties, threshold-prod ]

Results in:

TASK [debug] *******************************************************************
ok: [localhost] => (item=[u'absent', u'sys']) => {
    "msg": "state: absent; path: sys"
}
ok: [localhost] => (item=[u'absent', u'wifi']) => {
    "msg": "state: absent; path: wifi"
}
ok: [localhost] => (item=[u'absent', u'reco-properties']) => {
    "msg": "state: absent; path: reco-properties"
}
ok: [localhost] => (item=[u'absent', u'threshold-prod']) => {
    "msg": "state: absent; path: threshold-prod"
}
ok: [localhost] => (item=[u'directory', u'sys']) => {
    "msg": "state: directory; path: sys"
}
ok: [localhost] => (item=[u'directory', u'wifi']) => {
    "msg": "state: directory; path: wifi"
}
ok: [localhost] => (item=[u'directory', u'reco-properties']) => {
    "msg": "state: directory; path: reco-properties"
}
ok: [localhost] => (item=[u'directory', u'threshold-prod']) => {
    "msg": "state: directory; path: threshold-prod"
}

https://docs.ansible.com/ansible/2.4/playbooks_loops.html#nested-loops