Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 483
nik Avatar asked Aug 19 '16 13:08

nik


People also ask

How do I run multiple tasks in Ansible?

If you need to execute a task with Ansible more than once, write a playbook and put it under source control. Then you can use the playbook to push out new configuration or confirm the configuration of remote systems.

When with with_ items Ansible?

Ansible with_items plugin is a widely used plugin. You will use it whenever you need loop arrangement in your playbook, because this is the standard lookup used mostly. When we pass a list of items to a task, then task will be performed for all items in that list.

What is with_ items?

To use the with_items plugins, use the with_items keyword in a playbook and pass a list of items under it. You can then call each item within the specified list and perform the required operations.


2 Answers

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.

like image 63
techraf Avatar answered Oct 13 '22 22:10

techraf


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.

like image 44
Bent Blue Avatar answered Oct 13 '22 22:10

Bent Blue