对多项任务应用 with_items
Apply with_items on multiple tasks
是否可以将项目列表应用于 Ansible 剧本中的多个任务?举个例子:
- 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"
是否有一些语法可以避免重复项目列表?
从今天开始,您可以将 with_items
与 include
一起使用,因此您需要将剧本分成两个文件:
- name: download and execute
hosts: server1
tasks:
- include: subtasks.yml file={{item}}
with_items:
- "file1.sh"
- "file2.sh"
和subtasks.yml
:
- get_url: url="some-url/{{file}}" dest="/tmp/{{file}}"
- shell: /tmp/{{file}} >> somelog.txt
有一个 request 可以使 with_items
适用于 block
,但 Ansible 团队表示 它永远不会被支持 。
您可以在变量文件中定义一个 yaml 列表:
---
myfiles:
- "file1.sh"
- "file2.sh"
...
然后你可以使用
with_items: "{{ myfiles }}"
在任务中。
是否可以将项目列表应用于 Ansible 剧本中的多个任务?举个例子:
- 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"
是否有一些语法可以避免重复项目列表?
从今天开始,您可以将 with_items
与 include
一起使用,因此您需要将剧本分成两个文件:
- name: download and execute
hosts: server1
tasks:
- include: subtasks.yml file={{item}}
with_items:
- "file1.sh"
- "file2.sh"
和subtasks.yml
:
- get_url: url="some-url/{{file}}" dest="/tmp/{{file}}"
- shell: /tmp/{{file}} >> somelog.txt
有一个 request 可以使 with_items
适用于 block
,但 Ansible 团队表示 它永远不会被支持 。
您可以在变量文件中定义一个 yaml 列表:
---
myfiles:
- "file1.sh"
- "file2.sh"
...
然后你可以使用
with_items: "{{ myfiles }}"
在任务中。