Coder1
Coder1

Reputation: 13321

How can I create a role that includes tasks that should not run by default

Most of the tasks in my role should be run anytime the role is included, however, there are a couple tasks that I want to only be run when explicitly called.

For example, in my roles/elastic/tasks/main.yml file I have a lot of tasks which assure directories exist configure logstash and elasticsearch.

Now I want to create new set of tasks which initializes elasticsearch. i.e. It deletes existing data and creates/recreates schema.

I'm aware of tags, but I don't want all tasks to be run by accident if tags are not included when the role is run.

To run the playbook, I'm using ansible-playbook logserver.yml.

logserver.yml looks like this:

- hosts: localhost
  become: true
  roles:
    - common
    - elastic

I have tried adding a new task file, roles/elastic/tasks/init.yml, but I am having a hard time determining how to run that specific task file.

Upvotes: 2

Views: 666

Answers (2)

mvk_il
mvk_il

Reputation: 960

I am using "action" approach, to avoid conditions as much as possible. Usually there is a set of tasks you want to do and you can call it by single word action like name, e.g. "deploy", "disable". What I'm doing is

  1. For each such "action" I'm creating a distinct task list of the same name, like deploy.yml, disable.yml
  2. main.yml usually looks like:

    - include: '{{action}}.yml'
      when:
      - (action in ["deploy", "disable"])
    
  3. In vars/main.yml, I'm making sure one of the actions is always well defined even if role doesn't get variable action passed.

  4. Playbooks should either not pass action, relying on default, or pass it:

    - name: call role
      hosts: hg
      roles:
      - role:   user.role
        action: disable
    

This approach:

  • goes well with "divide & conquer"
  • still allows to include some "actions" in others if it makes sense
  • keeps tasklists short
  • is pretty easy to read

Upvotes: 0

m-p
m-p

Reputation: 346

If i'm understanding the question correctly, you could use a conditional on some tasks that relies on a variable set at the command line, with a default value that will fail the conditional check.

in scratch.yml:

---
- hosts: localhost
  vars: 
    my_var: "{{ MY_VAR|default('no') }}"

  tasks:
    - name: test 
      debug:
        msg: "my_var: {{ my_var }}"

    - name: test 2
      debug:
        msg: "in conditional"
      when: my_var == 'yes'

command line:

ansible-playbook scratch.yml

vs

ansible-playbook scratch.yml --extra-vars 'MY_VAR=yes'

Upvotes: 3

Related Questions