Automating Infrastructure with Ansible Roles and Publishing to Ansible Galaxy

Task Overview

This Task focuses on creating reusable Ansible roles to automate common infrastructure tasks such as web server setup, user management, and log rotation. The roles will be modular, configurable, and optimized for reusability. Once developed, they will be tested, documented, and published on Ansible Galaxy for public use.

Task Scope

Tech Stack

Step-by-Step Implementation

Step 1: Install Required Tools

Ensure you have the necessary tools installed on your system.

# Install Ansible
pip install ansible

# Install Molecule for testing
pip install molecule[docker]

# Install other dependencies
pip install ansible-lint pytest-testinfra

Step 2: Initialize Ansible Role Structure

Create the required roles using Ansible’s built-in ansible-galaxy command.

ansible-galaxy init ansible-role-webserver
ansible-galaxy init ansible-role-user-management
ansible-galaxy init ansible-role-log-rotation

This will generate a standard role structure:

ansible-role-webserver/
│── defaults/
│── handlers/
│── meta/
│── tasks/
│── templates/
│── tests/
│── vars/

Step 3: Define Role Functionality

Each role will have a specific purpose and configurations.

1. Web Server Setup Role

This role installs and configures Apache (or Nginx) on target systems.

2. User Management Role

This role creates users, assigns SSH keys, and manages groups.

3. Log Rotation Role

This role configures log rotation policies.

Step 4: Test Roles Using Molecule

Create a molecule test scenario for each role.

molecule init scenario --role-name ansible-role-webserver
molecule test

Step 5: Store in GitHub

Push the roles to GitHub for version control.

git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/yourusername/ansible-roles
git push -u origin main

Step 6: Publish to Ansible Galaxy

Login to Ansible Galaxy and publish the roles.

ansible-galaxy login
ansible-galaxy role import yourusername ansible-role-webserver

Verify the role is available at Ansible Galaxy.

Conclusion

This helps in standardizing automation and improving reusability for common system administration tasks.