I am setting up Ansible as a newbie. I would like to group a few tasks under an Nginx role.
See my folder structure
The only way I could get this to work is to use include statements in my playbooks... but that means I needed to start changing everything to relative paths since Ansible stopped being able to find things.
My playbook currently:
- name:
Install Nginx, Node, and Verdeccia
hosts:
all
remote_user:
root
tasks:
- include: ../roles/nginx/tasks/install.yml
- include: ../roles/nginx/tasks/create_node_config.yml
vars:
hostname: daz.com
How can I reference the sub task
in the playbook to be something like
tasks:
- nginx.install
and still be within best practices.
Your use of roles so far is not in line with the norm or the idea of Ansible. From a purely technical point of view, it is quite possible that you have multiple task bundles in yml files that you include in the playbook.
If you want to include a specific task file from a role, you should do this via the module include_role
with the parameter tasks_from
.
However, the workflow with roles usually looks different.
in the folder tasks
should always be a file main.yml
, this is called automatically if the role is included.
in this main.yml
you can then add further control logic to include your yml
files as required.
As it looks to me, for example, you always need to install, but depending on the use case you want to have different configurations.
create in your nginx
role a file defaults/main.yml
.
---
config_flavor: none
This initializes the config_flavor
variable with the string none
.
create in your nginx
role a file tasks/main.yml
.
---
- name: include installation process
include_tasks: install.yml
- name: configure node
include_tasks: create_node_config.yml
when: config_flavor == "node"
- name: configure symfony
include_tasks: create_symfony_config.yml
when: config_flavor == "symfony"
- name: configure wordpress
include_tasks: create_wordpress_config.yml
when: config_flavor == "wordpress"
main.yml
will be included by default when the role is applied.config_flavor
. In the listed example the values are node
, symfony
and wordpress
. In all other cases the installation will be done, but no configuration (so in the default case with none
).include your role in the playbook as follows
---
- name: Install Nginx, Node, and Verdeccia
hosts: all
remote_user: root
vars:
hostname: daz.com
roles:
- role: nginx
config_flavor: node
At this point you can set the value for config_flavor
. If you set wordpress
instead, the tasks create_wordpress_config.yml
will be included automatically, using the logic from tasks/main.yml
.
You can find more about roles in the Ansible Docs.
There are many more possibilities and ways, you will get to know them in the course of your learning. Basically I would recommend you to read a lot in the Ansible docs and to use them as a reference book.