ansible

Ansible execute each role in different host


My intention is to execute each role in a different host. I am doing a simple task of downloading files in each host. I have a host file which looks like so

[groupa]
10.0.1.20

[groupb]
10.0.1.21

below is my main_file.yml file

---
  - hosts: local
    connection: local
    gather_facts: no
    roles:
      - oracle
      - apache

Structure of my roles

main_file.yml
roles
|-- oracle
|   |-- tasks
|       |-- main.yml
|       |-- download_file.yml
|-- apache
|   |-- tasks
|       |-- main.yml
|       |-- download_file.yml

oracle/main.yml

---
- name: downloading a file in groupa
  hosts: groupa
  tasks:
    - include: tasks/download_file.yml

oracle/download_file.yml

---
- name: download file
  shell: wget http://dummyurl.com/random.sh

Same steps are followed for Apache role but for "groupb". But when I execute main_file.yml I am getting the below error

ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path.

The error appears to have been in '/etc/ansible/roles/oracle/tasks/main.yml': line 2, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

---
- name: downloading a file
  ^ here

Solution

  • In ansible there are two levels, one is the playbook level, the other one is the task level. On the playbook level you can specify which hosts you want to run the tasks on, but under the tasks level this is no longer possible, as the hosts have already been specified. Roles are included at the tasks level, so you cannot have hosts declarations inside them.

    You should remove the hosts from your main.yml, and only have the include:

    ---
    - name: downloading a file in groupa
      include: download_file.yml
    

    As roles are basically templates for a specific host, if you want them to run on a specific host just include them in your playbook accordingly. For example in your main_file.yml you can write the following:

    ---
    - hosts: groupa
      roles:
        - oracle
    
    - hosts: groupb
      roles:
        - apache
    
    - hosts: local
      connection: local
      tasks:
        - { debug: { msg: "Tasks to run locally" } }