DrMxxxxx
DrMxxxxx

Reputation: 15

Run all tasks in playbook with_items

I want the playbook to run once with each item in the list and not all items in the list at once.

Ansible version: 2.6.1

Tasks.yaml:

 ---

- name: Task 1
  debug:
    msg: "Message 1: {{ item }}"
  with_items: "{{ messages }}"

- name: Task 2
  debug:
    msg: "Message 2: {{ item }}"
  with_items: "{{ messages }}"

Playbook:

- hosts: localhost
  gather_facts: no
  tasks:
  - import_tasks: Tasks.yml
    vars:
      messages:
        - 1
        - 2

This is my expected result:

Task 1 with Item 1
Task 2 with Item 1
Task 3 with Item 1
Task 1 with Item 2
Task 2 with Item 2
Task 3 with Item 2
Task 1 with Item 3
Task 2 with Item 3
Task 3 with Item 3

But when I execute the playbook, then it is like this:

Task 1 with Item 1
Task 1 with Item 2
Task 2 with Item 1
Task 2 with Item 2
Task 3 with Item 1
Task 3 with Item 2
...

I tried both import and include - both have the same result.

Upvotes: 0

Views: 5633

Answers (1)

techraf
techraf

Reputation: 68439

Your playbook.yml should implement a loop (notice you cannot loop with import_tasks; it will raise an error):

- hosts: localhost
  connection: local
  gather_facts: no

  vars:
    messages:
      - 1
      - 2
      - 3

  tasks:
    - include_tasks: Tasks.yml
      loop: "{{ messages }}"

And Tasks.yml should look like this (no loops inside):

---
- name: Task 1
  debug:
    msg: "Message 1: {{ item }}"

- name: Task 2
  debug:
    msg: "Message 2: {{ item }}"

Upvotes: 4

Related Questions