How to specify ansible pretasks for a role?

Kęstutis picture Kęstutis · Mar 25, 2015 · Viewed 72.3k times · Source

How should one go about defining a pretask for role dependencies. I currently have an apache role that has a user variable so in my own role in <role>/meta/main.yml I do something like:

---
dependencies:
  - { role: apache, user: proxy }

The problem at this point is that I still don't have the user I specify and when the role tries to start apache server under a non existent user, I get an error.

I tried creating a task in <role>/tasks/main.yml like:

---
- user: name=proxy

But the user gets created only after running the apache task in dependencies (which is to be expected). So, is there a way to create a task that would create a user before running roles in dependencies?

Answer

Chu-Siang Lai picture Chu-Siang Lai · May 3, 2016

I use the pre_tasks to do some tasks before roles, thanks for Kashyap.

#!/usr/bin/env ansible-playbook

---
- hosts: all
  become: true
  pre_tasks:
    - name: start tasks and sent notifiaction to HipChat
      hipchat:
        color: purple
        token: "{{ hipchat_token }}"
        room: "{{ hipchat_room }}"
        msg: "[Start] Run 'foo/setup.yml' playbook on {{ ansible_nodename }}."

  roles:
    - chusiang.vim-and-vi-mode

  vars:
    ...

  tasks:
    - name: include main task
      include: tasks/main.yml

  post_tasks:
    - name: finish tasks and sent notifiaction to HipChat
      hipchat:
        color: green
        token: "{{ hipchat_token }}"
        room: "{{ hipchat_room }}"
        msg: "[Finish] Run 'foo/setup.yml' playbook on {{ ansible_nodename }}."

# vim:ft=ansible :