Creating Roles in Ansible
Introduction
Ansible roles allow you to break down your playbooks into reusable components. Roles are a way to group multiple tasks together in a reusable and organized manner. This tutorial will guide you through the process of creating roles in Ansible from start to finish.
Step 1: Setting Up Your Project Directory
Before we create a role, we need to set up our project directory. This directory will contain all your Ansible configurations.
mkdir my-ansible-project
cd my-ansible-project
Step 2: Creating the Role Directory Structure
Ansible provides a command to create the basic directory structure for a role. This structure includes directories for tasks, handlers, variables, and more.
ansible-galaxy init my_role
- my_role/ - defaults/ - main.yml - files/ - handlers/ - main.yml - meta/ - main.yml - tasks/ - main.yml - templates/ - tests/ - inventory - test.yml - vars/ - main.yml
Step 3: Defining Tasks
Tasks are the actions that your role will perform. Tasks are defined in the tasks/main.yml
file. Let's add a simple task to install a package.
tasks/main.yml: - name: Install Nginx apt: name: nginx state: present
Step 4: Using Variables
Variables allow you to make your roles more flexible and reusable. You can define default variables in the defaults/main.yml
file.
defaults/main.yml: nginx_package: nginx tasks/main.yml: - name: Install Nginx apt: name: "{{ nginx_package }}" state: present
Step 5: Adding Handlers
Handlers are special tasks that are run only when notified. They are typically used to restart services. Handlers are defined in the handlers/main.yml
file.
handlers/main.yml: - name: restart nginx service: name: nginx state: restarted tasks/main.yml: - name: Install Nginx apt: name: "{{ nginx_package }}" state: present notify: restart nginx
Step 6: Using Templates
Templates allow you to create files dynamically based on variables. Templates are placed in the templates
directory and typically use the Jinja2 templating language.
templates/nginx.conf.j2: server { listen 80; server_name {{ nginx_host }}; location / { proxy_pass http://127.0.0.1:8080; } } tasks/main.yml: - name: Install Nginx apt: name: "{{ nginx_package }}" state: present notify: restart nginx - name: Deploy Nginx Configuration template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: restart nginx defaults/main.yml: nginx_package: nginx nginx_host: localhost
Step 7: Testing Your Role
To test your role, you can create a simple playbook in the root of your project directory. This playbook will include your role.
test.yml: - hosts: localhost roles: - my_role inventory: localhost ansible_connection=local
ansible-playbook -i inventory test.yml