I'm pretty new to ansible so I might be setting up things wrong. My idea is I have certain classes of servers. (monitor,web,db for example)
I want to run a local ansible run on them so my play for monitor looks something like
---
# plays/monitor.yaml
- hosts: mongo
connection: local
hosts: localhost
become: yes
become_user: root
roles:
- ../roles/users
- ../roles/monitor
vars:
sensu_install_client: true
sensu_install_server: true
My roles/monitor/tasks/main.yml
looks like
---
# roles/monitor/tasks/main.yaml
- include: common.yml
- include: server.yml
when: sensu_install_server
- include: client.yml
when: sensu_install_client
I want to be able to pass in vars so includes will happen in the role. So when I setup my api instances I can do something like
vars:
sensu_install_client: true
In the play and it will just include the client.yml from the monitor role.
It's not clear to me why this is not working. I can't see a problem. But let me give you some general recommendations, maybe that'll help you too.
Best practice is to have your playbooks on the root level. Have a look at this structure. With that setup, you do not need to specify the path to the roles as Ansible automatically expects roles in the
roles
directory relative to the playbook. Then your roles section in the playbook is much cleaner:Instead of defining global variables to trigger actions inside roles you can use two other approaches.
1. role parameters
Roles can have parameters. If you want to pass parameters you simply have to convert it to a dictionary:
The variables
sensu_install_client
andsensu_install_server
then are available only in the rolemonitor
. This is a litte more cleaner and also makes it clear to anybody these vars will be used in this role, not in theusers
role.2. tags
Tags actually are the way how to trigger specific parts of a playbook/roles. Tags though are passed from the command line and not by hardcoded variables in the playbook. Imagine your role
main.yml
looks like this:The tag
always
is special and will run the tagged tasks... well you guessed it... always.Now you would call your playbook like this:
or
Or if you want to run both you even could do:
If you use this, don't forget to tag your users role accordingly, or it will not be ran at all.
If you do not specify any
--tags
all tasks are executed, if you want to filter specific tags you can use the--skip-tags
optionYou could even filter the always tag.