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.
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
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/
Each role will have a specific purpose and configurations.
This role installs and configures Apache (or Nginx) on target systems.
- name: Install Apache
package:
name: apache2
state: present
when: ansible_os_family == "Debian"
- name: Ensure Apache service is started
service:
name: apache2
state: started
enabled: yes
---
webserver_package: apache2
---
- name: Restart Apache
service:
name: apache2
state: restarted
This role creates users, assigns SSH keys, and manages groups.
- name: Create users
user:
name: "{{ item.name }}"
state: present
shell: /bin/bash
with_items: "{{ users }}"
---
users:
- name: "deploy"
- name: "admin"
This role configures log rotation policies.
- name: Copy logrotate configuration
template:
src: logrotate.j2
dest: /etc/logrotate.d/custom_logs
/var/log/custom/*.log {
daily
rotate 7
compress
missingok
}
Create a molecule test scenario for each role.
molecule init scenario --role-name ansible-role-webserver
molecule test
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
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.
This helps in standardizing automation and improving reusability for common system administration tasks.