ansible playbook execute in this order: task, role, task, role, task

39.6k Views Asked by At

Forgive my newbie question, but I would like to execute three tasks and use two roles in a playbook, in the order:

  1. task
  2. role
  3. task
  4. role
  5. task

This is what I have so far (task, role, task):

---
- name: Task Role Task
  hosts: 127.0.0.1
  connection: local
  gather_facts: false

  pre_tasks:
   - name: Do this task first
     foo:

  roles:
  - role: this role second
    foo:

  post_tasks: 
   - name: Do this task third
     foo:

Is this possible or should I be changing my tasks into roles?

3

There are 3 best solutions below

1
On BEST ANSWER

I recommend you create roles for post and pre tasks for you ansible.

Your site.yml must be some like this:

---
- hosts: localhost
  remote_user: "{{remote_user}}"
  sudo: yes
  gather_facts: false
  roles:
    - pre
    - main_role
    - post

in roles folder you must have three roles, pre, post and main_role.

4
On
---
- name: Task Role Task
  hosts: 127.0.0.1
  connection: local
  gather_facts: false

  tasks:
    - name: task1
      foo: 

    - name: include role1
      include_role: 
        name: myrole1

    - name: task2
      foo:

    - name: include role2
      include_role: 
        name: myrole2

see official docs

1
On

Each "hosts:"-block will be executed one by one. So you can use multiple blocks to force the desired execution order:

---
- hosts: 127.0.0.1
  tasks:
   - name: Do this task first

- hosts: 127.0.0.1
  roles:
  - role: this role second

- hosts: 127.0.0.1
  tasks:
   - name: Do this task third