Vikki Lohana
Vikki Lohana

Reputation: 59

How to Execute Role Inside the Ansible Blocks

I have written a ansible playbook which do a deployment on the remote machines

-   name: Deployment part of the script
    vars:
       hostName: 
       build_num: 
    hosts: "{{hostName}}"
    become: true
    serial: 1
    tasks: this does deployment

after this I want to execute the util which is on localhost from where this playbook will be executed.

Now I have written a roles which does this for me if I execute them separately as a playbook


  - name: Roles Demo
    hosts: 127.0.0.1
    connection: local
    vars: 
       var1: "sometextvalue"
       var2: "sometextvalue"
       var3: "someurl" 
    roles: 
    - demorole #role which I created

Now I want to integrate the role in my main playbook mentioned at the top but I am getting

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

although its the same snippet which is working fine when run individually

Also I wanted to execute this using "Ansible blocks" like when a certain condition is matched execute a certain role but for that also I am getting the same above error just to summarize what I want to achieve using the blocks is as below

-   name: Deployment part of the script
    vars:
       hostName: 
       build_num: 
    hosts: "{{hostName}}"
    become: true
    serial: 1
    tasks: this does deployment complete
- name: Task for Doing some check
  hosts: 127.0.0.1
  connection: local
  vars:
      var1: "dakdkadadakdhkahdkahkdh
      var2: "jdjaldjlaj"
      var3: "djasjdlajdlajdljadljaldjlaj"
  block: 
  - name: Doing Check for some1
    roles: 
    - role1
  when: x == "somevalue1"
- block: 
  - name: Doing check for some2
    roles: 
    - role2
  when: x == "somevalue2"
.
.
.
assuming the vars value are same

so I am not sure if this could be achieved

Upvotes: 2

Views: 8521

Answers (1)

Matt P
Matt P

Reputation: 2625

Using a block outside of the tasks section is not valid.

You can however execute roles from within the tasks section, which will allow you to use blocks and when conditionals however you choose.

Example:

- name: Task for Doing some check
  hosts: 127.0.0.1
  connection: local
  vars:
      var1: "dakdkadadakdhkahdkahkdh
      var2: "jdjaldjlaj"
      var3: "djasjdlajdlajdljadljaldjlaj"
  tasks:
    - name: Doing Check for some1
      import_role:
        name: role1
      when: x == "somevalue1"

You will need to decide whether to use import_role or include_role. Take a look at https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse.html#dynamic-vs-static for an explanation of the differences.

Upvotes: 1

Related Questions