Reputation: 13321
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
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
deploy.yml
, disable.yml
main.yml
usually looks like:
- include: '{{action}}.yml'
when:
- (action in ["deploy", "disable"])
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.
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:
Upvotes: 0
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