Day-05 | Ansible Galaxy Tutorial: Write Less Code, Leverage Existing Roles
In this chapter, we explore Ansible Galaxy, the official public registry and marketplace for Ansible content. We will examine how to avoid writing complex configuration management code from scratch by leveraging pre-built, community-tested roles. Additionally, we will walk through the complete lifecycle of finding, installing, executing, and publishing custom Ansible roles to the global community.
1. Recap of the Ansible Journey (Days 1–4)
Before diving into Ansible Galaxy, it is helpful to understand how the building blocks of Ansible fit together. The table below summarizes the progression from basic execution to modular code structures.
2. The Problem: Multi-OS Configuration Complexity
When writing Ansible playbooks from scratch, simple tasks can quickly become complex when targeting heterogeneous environments.
The Scenario: Installing Docker Across Multiple Operating Systems
Consider a scenario where your Ansible control node must install and configure Docker across a fleet of managed nodes running different Linux distributions:
To handle this natively in a single playbook, you would have to write highly conditional code:
- Package Management: Red Hat uses
yum/dnf, Debian/Ubuntu usesapt, and Alpine usesapk. - User Creation: System commands and flags for adding users to the
dockergroup vary by OS. - Service Management: Systemd commands (
systemctl) vs. SysV init or OpenRC commands.
The Naive Approach (Monolithic Playbook with Conditionals)
---
- hosts: all
become: true
tasks:
- name: Install Docker on Debian/Ubuntu
apt:
name: docker.io
state: present
when: ansible_os_family == "Debian"
- name: Install Docker on Red Hat
yum:
name: docker
state: present
when: ansible_os_family == "RedHat"
# Additional tasks for service start, user groups, and compose setups...
This approach leads to bloated, hard-to-maintain playbooks filled with when conditionals. Instead of reinventing the wheel, DevOps engineers use Ansible Galaxy to find pre-written, robust roles that have already solved these multi-OS compatibility challenges.
3. The Mental Model: What is Ansible Galaxy?
Real-Life Analogy
Ansible Galaxy is to Ansible Roles what Docker Hub is to Docker Images. Just as you pull pre-configured container images (like
nginxorubuntu) from Docker Hub using the Docker CLI, you pull pre-configured configuration roles (likedocker,jenkins, ormysql) from Ansible Galaxy using theansible-galaxyCLI.
Ansible Galaxy serves as a public directory where thousands of system administrators and DevOps engineers share modular, configuration-ready roles.
4. Anatomy of the ansible-galaxy CLI
The ansible-galaxy command-line utility is bundled automatically with your Ansible installation. It is used to manage both collections and roles.
To view the help menu for roles, execute:
ansible-galaxy role -h
Core CLI Commands
5. Step-by-Step: Finding and Installing a Role
Let's walk through finding and installing a community-approved Docker role.
Step 1: Search the Registry
- Navigate to galaxy.ansible.com.
- Search for
docker. - Look for highly rated, widely downloaded roles (e.g., roles tested across Ubuntu, Debian, and Red Hat).
- Review the role's GitHub repository to verify code quality and check the
tasks/directory to ensure it is safe and well-maintained.
Step 2: Install the Role Locally
To install a role, use the ansible-galaxy role install command followed by the author and role name:
ansible-galaxy role install geerlingguy.docker
Step 3: Verify the Installation Path
By default, Ansible downloads external roles into a hidden directory in your user's home path: ~/.ansible/roles/.
To verify where the files were saved, list the contents of that directory:
ls -la ~/.ansible/roles/
Inside this directory, you will see the downloaded role structure:
Note: The downloaded role contains separate task files (e.g.,
setup-Debian.yml,setup-RedHat.yml) to handle different operating systems automatically.
6. Step-by-Step: Using an Installed Galaxy Role in a Playbook
Once a role is installed in ~/.ansible/roles/, Ansible can reference it globally. You do not need to copy the role files into your local project directory.
Step 1: Create the Playbook
Create a new playbook file named docker-playbook.yml:
---
- hosts: all
become: true
roles:
- geerlingguy.docker
Step 2: Execute the Playbook
Run the playbook against your inventory (configured in Day 2):
ansible-playbook -i inventory docker-playbook.yml
Step 3: Verify the Installation on Managed Nodes
Log into one of your managed EC2 instances and verify that Docker was installed, configured, and started successfully:
docker --version
systemctl status docker
7. Step-by-Step: Publishing Your Own Role to Ansible Galaxy
Sharing your custom roles with your team or the wider community involves hosting the code on GitHub and importing it into Ansible Galaxy.
Local Role Directory (e.g., httpd)
|
| git push
v
Public GitHub Repository (e.g., dummy-role)
|
| ansible-galaxy import
v
Ansible Galaxy Registry (Publicly Available)
Step 1: Prepare Your Local Role
Ensure your role directory (e.g., the httpd role created in Day 4) is clean and contains a meta/main.yml file.
The Importance of meta/main.yml
The meta/main.yml file contains metadata about your role. Ansible Galaxy reads this file to populate your role's details page.
galaxy_info:
author: Abhishek Veermalla
description: A dummy Apache HTTPD installation role for demonstration purposes.
company: Community
license: MIT
min_ansible_version: 2.9
platforms:
- name: EL
versions:
- 8
- name: Ubuntu
versions:
- focal
categories:
- system
dependencies: []
Step 2: Push the Role to a Public GitHub Repository
Ansible Galaxy requires roles to be hosted in a public GitHub repository.
- Log into GitHub and create a new public repository named
ansible-role-httpd(ordummy-role). - Initialize Git in your local role directory and push the code:
# Navigate to your role directory
cd /path/to/ansible/roles/httpd
# Initialize Git
git init
# Add remote origin
git remote add origin https://github.com/your-username/ansible-role-httpd.git
# Stage and commit files
git add .
git commit -m "Initial commit of httpd role"
# Rename branch to main and push
git branch -M main
git push -u origin main
Step 3: Authenticate with Ansible Galaxy
- Go to galaxy.ansible.com and click Login in the top-right corner.
- Authenticate using your GitHub Account.
- Once logged in, navigate to your profile/account settings to find your API Token.
- Copy the API Token.
Step 4: Import the Role via CLI
Use the ansible-galaxy import command, passing your GitHub username, repository name, and your API token:
ansible-galaxy import your-github-username ansible-role-httpd --token YOUR_GALAXY_API_TOKEN_HERE
Step 5: Verify on Ansible Galaxy
- Refresh your Ansible Galaxy dashboard.
- Navigate to your namespace (e.g.,
your-github-username). - Your newly published role will now be visible and available for anyone to install using:
BASH
ansible-galaxy role install your-github-username.ansible-role-httpd
8. Best Practices & Production Pitfalls
1. Document Your Roles (README.md)
When publishing roles, always write a clear README.md file. It should document:
- Role Variables: What variables can be overridden in
defaults/main.yml? - Dependencies: Does this role require other roles to run first?
- Example Playbook: Show users exactly how to call your role.
2. Secure Your API Tokens
Never hardcode your Ansible Galaxy API token in scripts or commit it to version control.
Tip: You can store your token in an environment variable or configure it in your local
ansible.cfgfile:INI[galaxy] token = YOUR_GALAXY_API_TOKEN_HERE
3. Verify Community Roles Before Running Them
Because anyone can publish to Ansible Galaxy, always inspect the source code of a third-party role before running it with elevated privileges (become: true) on production servers. Look for:
- Active maintenance (recent commits, open issues resolved).
- Clear, readable task files without obfuscated shell scripts.
- Hardcoded credentials or insecure default configurations.
9. Complete Flow Walkthrough
This workflow shows how a DevOps engineer uses Ansible Galaxy to install Docker and then publishes a custom web server role back to the registry.
10. Summary and Key Takeaways
- Ansible Galaxy is a public registry that helps you find, share, and reuse community-tested Ansible roles.
- Using existing roles reduces development time and helps you avoid writing complex OS-specific conditional logic.
- The
ansible-galaxyCLI is bundled with Ansible and manages the entire lifecycle of roles and collections. - External roles are installed by default to the
~/.ansible/roles/directory on your control node. - To use a Galaxy role, simply reference its name under the
roles:key in your playbook. - To publish a role, it must be hosted in a public GitHub repository and imported using an Ansible Galaxy API token.
- Always populate the
meta/main.ymlandREADME.mdfiles to ensure your published roles are documented and easy to use.