Expanding Our Role
Now that we have a basic role structure, let's expand it to include more components of a typical Ansible role. We'll add variables, a handler, and a template.
First, let's add a default variable. Create a main.yml
file in the defaults
directory:
nano defaults/main.yml
Add the following content:
---
example_variable: "This is a default value"
This sets a default value for example_variable
, which can be overridden when the role is used.
Next, let's create a handler. Create a main.yml
file in the handlers
directory:
nano handlers/main.yml
Add the following content:
---
- name: Restart example service
debug:
msg: "This would restart a service in a real scenario"
In a real-world scenario, this handler might restart a service, but for this example, we're just printing a message.
Now, let's create a template. Create a file named example_template.j2
in the templates
directory:
nano templates/example_template.j2
Add the following content:
This is an example template.
The value of example_variable is: {{ example_variable }}
This template uses Jinja2 syntax to include the value of our example_variable
.
Finally, let's update our tasks/main.yml
to use these new components:
nano tasks/main.yml
Replace the existing content with:
---
- name: Print a message
debug:
msg: "This is a task from our example role!"
- name: Use our variable
debug:
msg: "The value of example_variable is: {{ example_variable }}"
- name: Create a file from our template
template:
src: example_template.j2
dest: /tmp/example_file.txt
notify: Restart example service
This updated task list now uses our variable, creates a file from our template, and notifies our handler.