'can roles and tasks exist in the same playbook?

---
# file: main.yml

- hosts: fotk
  remote_user: fakesudo
  tasks:
  - name: create a developer user
    user: name={{ user }}
          password={{ password }}
          shell=/bin/bash
          generate_ssh_key=yes
          state=present
  roles:
  - { role: create_developer_environment, sudo_user: "{{ user }}" }
  - { role: vim, sudo_user: "{{ user }}" }

For some reason the create user task is not running. I have searched every key phrase I can think of on Google to find an answer without success.

The roles are running which is odd.

Is it possible for a playbook to contain both tasks and roles?



Solution 1:[1]

You can also do pre_tasks: and post_tasks: if you need to do things before or after. From the Docs https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html

- hosts: localhost

  pre_tasks:
    - shell: echo 'hello in pre'

  roles:
    - { role: some_role }

  tasks:
    - shell: echo 'in tasks'

  post_tasks:
    - shell: echo 'goodbye in post'

Gives the output: PLAY [localhost]


GATHERING FACTS *************************************************************** ok: [localhost]

TASK: [shell echo 'hello in pre'] ********************************************* changed: [localhost]

TASK: [some_role | shell echo 'hello from the role'] ************************** changed: [localhost]

TASK: [shell echo 'in tasks'] ************************************************* changed: [localhost]

TASK: [shell echo 'goodbye in post'] ****************************************** changed: [localhost]

PLAY RECAP ******************************************************************** localhost : ok=5 changed=4 unreachable=0
failed=0

This is with ansible 1.9.1

Solution 2:[2]

https://docs.ansible.com/playbooks_roles.html#roles

If the play still has a ‘tasks’ section, those tasks are executed after roles are applied.

If you wish to run tasks before or after roles are executed, you need to list these under pre_tasks and post_tasks. Thus, there is no way to run "loose" tasks between two roles. You might want to create a dedicated role for these tasks.

Solution 3:[3]

Short follow up to the already mentioned options by quoting the latest Ansible docs docs.ansible.com/latest/playbooks_reuse_roles:

As of Ansible 2.4, you can now use roles inline with any other tasks using import_role or include_role:

---    
- hosts: webservers
  tasks:
    - debug:
      msg: "before we run our role"
    - import_role:
      name: example
    - include_role:
      name: example
    - debug:
      msg: "after we ran our role"`

Code snippet is also from Ansible docs.

Be aware of the difference between static (import*) & dynamic (include*) usage.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Dresko
Solution 2 Régis B.
Solution 3 Community