在多个任务上应用with_items

nik*_*nik 17 ansible ansible-playbook

是否可以将项目列表应用于Ansible playbook中的多个任务?举个例子:

- name: download and execute
  hosts: server1
  tasks:
  - get_url: url="some-url/{{item}}" dest="/tmp/{{item}}"
    with_items:
    - "file1.sh"
    - "file2.sh"
  - shell: /tmp/{{item}} >> somelog.txt
    with_items:
    - "file1.sh"
    - "file2.sh"
Run Code Online (Sandbox Code Playgroud)

是否有一些语法可以避免重复项目列表?

tec*_*raf 20

截至今天,你可以用with_itemsinclude,所以你需要将剧本拆分成两个文件:

- name: download and execute
  hosts: server1
  tasks:
  - include: subtasks.yml file={{item}}
    with_items:
    - "file1.sh"
    - "file2.sh"
Run Code Online (Sandbox Code Playgroud)

并且subtasks.yml:

- get_url: url="some-url/{{file}}" dest="/tmp/{{file}}"
- shell: /tmp/{{file}} >> somelog.txt
Run Code Online (Sandbox Code Playgroud)

有一个请求,使with_items适用block,但它仍然没有实现.


小智 5

您可以在变量文件中定义yaml列表:

---
myfiles:
- "file1.sh"
- "file2.sh"
...
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

with_items: "{{ myfiles }}"
Run Code Online (Sandbox Code Playgroud)

在任务中.