在一个任务中使用两个with_items循环

时间:2019-04-17 17:50:22

标签: ansible

我在这个问题上做了很多研究。尽管我没有找到解决问题的答案。

我想通过删除目录本身来删除带有ansibe的目录内容。我想对多个目录执行此操作。

理论上我想做这样的事情:

- 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

不幸的是,这不起作用。 这就是我现在所拥有的。

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

是否可以通过创建两个循环来使这段代码更短?

1 个答案:

答案 0 :(得分:1)

您要with_nested

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

结果:

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

相关问题