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

问题描述 投票:1回答:1

我对这个问题做了很多研究。虽然我找不到解决问题的答案。

我想删除目录内容与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

有没有办法通过创建两个循环来缩短此代码?

ansible
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.