DEV Community

Cover image for Day-13 Refactoring Ansible Playbooks into Roles πŸš€
Jayanth Dasari
Jayanth Dasari

Posted on

Day-13 Refactoring Ansible Playbooks into Roles πŸš€

Today I dived deeper into Ansible, moving from simple ad-hoc commands to full-blown Playbooks and Roles. Here is what I built! πŸ› οΈ

πŸ“ The Playbook
I started by writing a basic YAML playbook to automate which Installs apache2 and copies the index.html page to /var/www/html
and runs the webserver
The beauty of it? If I run it twice, Ansible knows nothing needs to change. That idempotency is a game-changer. It was satisfying to see the tasks execute sequentially:

YAML

- name: Installing and running apache2
  hosts: all
  roles:
    - httpd
Enter fullscreen mode Exit fullscreen mode

πŸ“¦ Leveling Up with Roles
I quickly realized that a single playbook file gets hard to read. I learned about Ansible Roles, which is the standard way to organize automation code.

I created my first role structure:

roles/
└── my-app/
    β”œβ”€β”€ tasks/
    β”‚   └── main.yml
    β”œβ”€β”€ handlers/
    β”‚   └── main.yml
    └── vars/
        └── main.yml
Enter fullscreen mode Exit fullscreen mode

This makes the code reusable. If I need this configuration again, I just call the role!

πŸ”— The Code
I’ve pushed my first role to GitHub. I’m trying to keep my commits clean and my structure organized.

Check it out here: https://github.com/JayanthDasari7/Ansible-Roles
linkedinΒ :https://www.linkedin.com/in/dasari-jayanth-b32ab9367/

Has anyone else here struggled with the directory structure of Roles initially? Let me know in the comments! πŸ‘‡

Top comments (0)