Ansible: run certain yaml tasks file for all hosts

Viewed 403

I try to run certain yaml tasks file for all hosts, as follows (main.yml):

- name: prepare nodes
  include_tasks: node.yml node="{{ item }}"
  loop: "{{ groups['all'] }}"

node.yml:

- block:
    - name: Task 1...

    ...

    - name: Task 100...

  delegate_to: "{{ node }}"

However I get this error: Invalid options for include_tasks: node. I think it used to work in this manner. Anyway I tried to move loop from main.yml into node.yml (right after delegate_to). I also tried to skip node="{{ item }}" part. But I always get errors.

What is the proper way to apply a task file to several hosts within a role?

2 Answers

A play runs on the hosts you specified. You can run certain tasks on a subset of nodes using when.

But you can have multiple plays in a playbook. So you need to specify a play with hosts: all where you run the tasks you want to run everywhere and another one which runs the rest of the tasks.
Your playbook could look like this:

---
# This is a play
- name: run on all
  hosts: all
  vars:
    somevar: 'test'
  tasks:
    - name: prepare nodes
      include_tasks: node.yml

# This is another play
- name: run on group
  hosts: hostgroup
  vars:
    somevar: 'example'
  tasks:
    - debug:
        msg: 'This runs on all hosts in hostgroup'

# Both plays are in the same playbook

It should work if you put your node variable under vars then loop.

- name: include tasks
  include_tasks: node.yml
  vars:
    node: '{{ item }}'
  loop: "{{ groups['all'] }}" 

Above code is working.

Related