nik
nik

Reputation: 2294

Apply with_items on multiple tasks

Is it possible to apply a list of items to multiple tasks in an Ansible playbook? To give an example:

- 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"

Is there some syntax to avoid the repetition of the item-list?

Upvotes: 27

Views: 52494

Answers (2)

techraf
techraf

Reputation: 68479

As of today you can use with_items with include, so you'd need to split your playbook into two files:

- name: download and execute
  hosts: server1
  tasks:
  - include: subtasks.yml file={{item}}
    with_items:
    - "file1.sh"
    - "file2.sh"

and subtasks.yml:

- get_url: url="some-url/{{file}}" dest="/tmp/{{file}}"
- shell: /tmp/{{file}} >> somelog.txt

There was a request to make with_items applicable to block, but the Ansible team has said it will never be supported.

Upvotes: 43

Bent Blue
Bent Blue

Reputation: 166

You have the possibility to define a yaml list in a variables file:

---
myfiles:
- "file1.sh"
- "file2.sh"
...

and then you can use

with_items: "{{ myfiles }}"

in the task.

Upvotes: 5

Related Questions