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.
2
Answers
Please refer to bellow document. you can use "include_role" with "tasks_from" attribute. you don’t need to provide full path of task files, Just file names.
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/include_role_module.html
Example:
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 better do this via the module
include_role
with the parametertasks_from
.However, the workflow with roles usually looks different.
in the folder
tasks
should always be a filemain.yml
, this is called automatically, if simply the role is included, no matter over which way.in this
main.yml
you can then add further control logic to include youryml
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 filedefaults/main.yml
.This initializes the
config_flavor
variable with the stringnone
.create in your
nginx
role a filetasks/main.yml
.main.yml
will be included by default when the role is applied.config_flavor
. In the listed example the values arenode
,symfony
andwordpress
. In all other cases the installation will be done, but no configuration (so in the default case withnone
).include your role in the playbook as follows
At this point you can set the value for
config_flavor
. If you setwordpress
instead, the taskscreate_wordpress_config.yml
will be included automatically, using the logic fromtasks/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.