Skip to main content

Ansible Galaxy

Introduction

Ansible Galaxy is a hub for finding, reusing, and sharing Ansible content. Think of it as the "npm" for Node.js or "PyPI" for Python, but specifically for Ansible roles and collections. Galaxy provides a centralized repository where developers can share their Ansible roles with the community, making it easier to automate infrastructure tasks without starting from scratch.

In this tutorial, we'll explore how Ansible Galaxy works, how to find and use existing roles, and how to create and share your own roles with the community.

What is Ansible Galaxy?

Ansible Galaxy serves several important purposes in the Ansible ecosystem:

  1. Finding Roles: It helps you discover pre-built roles created by the community
  2. Sharing Roles: You can publish your own roles for others to use
  3. Standardization: It promotes best practices in role development
  4. Version Control: It manages different versions of roles
  5. Dependencies: It handles role dependencies automatically

Installing Ansible Galaxy

The Ansible Galaxy command-line tool comes bundled with Ansible. If you have Ansible installed, you already have access to the ansible-galaxy command.

To verify your installation, run:

bash
ansible-galaxy --version

You should see output similar to:

ansible-galaxy [core 2.14.1]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3.10/site-packages/ansible
ansible collection location = /home/user/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/bin/ansible-galaxy
python version = 3.10.6 (main, May 29 2023, 11:10:38) [GCC 12.3.0] (/usr/bin/python3)
jinja version = 3.1.2
libyaml = True

Finding and Installing Roles

Searching for Roles

You can search for Ansible roles either through the Ansible Galaxy website or via the command line:

bash
ansible-galaxy search nginx

This will return a list of roles related to nginx:

Found 1234 roles matching your search. Showing first 1000.

Name Description
---- -----------
geerlingguy.nginx Nginx installation for Linux, FreeBSD and OpenBSD.
nginxinc.nginx Official Ansible role for NGINX
ansible-galaxy-roles.nginx Install and configure Nginx
# ... more results

Role Information

To get more details about a specific role:

bash
ansible-galaxy info geerlingguy.nginx

Output:

Role: geerlingguy.nginx
description: Nginx installation for Linux, FreeBSD and OpenBSD.
active: True
commit: d7e75eced9619033e937da97e239d2587eea6ad6
commit_message: Issue #329: Update Debian 10 testing to 11.
commit_url: https://github.com/geerlingguy/ansible-role-nginx/commit/d7e75eced9619033e937da97e239d2587eea6ad6
company: Midwestern Mac, LLC
created: 2015-01-09T13:33:43.040Z
download_count: 26915129
forks_count: 1198
# ... more details

Installing Roles

To install a role from Galaxy:

bash
ansible-galaxy install geerlingguy.nginx

Output:

Starting galaxy role install process
- downloading role 'nginx', owned by geerlingguy
- downloading role from https://github.com/geerlingguy/ansible-role-nginx/archive/3.0.0.tar.gz
- extracting geerlingguy.nginx to /home/user/.ansible/roles/geerlingguy.nginx
- geerlingguy.nginx (3.0.0) was installed successfully

By default, roles are installed to ~/.ansible/roles. You can specify a different location with the -p or --roles-path option:

bash
ansible-galaxy install geerlingguy.nginx -p ./roles

Installing Multiple Roles

You can install multiple roles at once using a requirements file. Create a file named requirements.yml:

yaml
# requirements.yml
- name: geerlingguy.nginx
version: 3.0.0

- name: geerlingguy.mysql
version: 3.3.0

Then install all roles defined in the file:

bash
ansible-galaxy install -r requirements.yml

Using Installed Roles in Your Playbooks

Once you've installed a role, you can use it in your playbooks:

yaml
---
- hosts: webservers
roles:
- geerlingguy.nginx

You can also customize role variables:

yaml
---
- hosts: webservers
roles:
- role: geerlingguy.nginx
vars:
nginx_vhosts:
- listen: "80"
server_name: "example.com"
root: "/var/www/example"
index: "index.php index.html index.htm"

Creating Your Own Ansible Galaxy Role

Initializing a New Role

You can create a new role structure using the ansible-galaxy command:

bash
ansible-galaxy init my_custom_role

This creates a directory structure for your role:

my_custom_role/
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml

Role Structure Explanation

Let's understand each component:

  1. defaults/main.yml: Default variables for the role that can be overridden
  2. files: Contains static files that can be deployed via the role
  3. handlers/main.yml: Contains handlers that can be triggered by tasks
  4. meta/main.yml: Contains role metadata including dependencies
  5. tasks/main.yml: The main list of tasks that the role executes
  6. templates: Contains Jinja2 templates that can be deployed via the role
  7. tests: Contains tests for the role
  8. vars/main.yml: Contains variables for the role that are not meant to be overridden

Example: Creating a Simple Web Server Role

Let's create a simple role for setting up a web server:

  1. First, edit the meta/main.yml file to include role metadata:
yaml
---
galaxy_info:
author: Your Name
description: Simple web server role
company: Your Company (optional)
license: MIT
min_ansible_version: 2.9
platforms:
- name: Ubuntu
versions:
- all
- name: Debian
versions:
- all
galaxy_tags:
- web
- nginx
- server

dependencies: []
  1. Edit the defaults/main.yml to define default variables:
yaml
---
# Default web server port
web_server_port: 80

# Default document root
web_server_root: /var/www/html

# Default index file
web_server_index: index.html
  1. Edit the tasks/main.yml file to define the tasks:
yaml
---
- name: Install nginx
package:
name: nginx
state: present
become: true

- name: Create document root
file:
path: "{{ web_server_root }}"
state: directory
owner: www-data
group: www-data
mode: '0755'
become: true

- name: Configure nginx
template:
src: nginx.conf.j2
dest: /etc/nginx/sites-available/default
owner: root
group: root
mode: '0644'
become: true
notify: Restart nginx
  1. Create a template in templates/nginx.conf.j2:
jinja
server {
listen {{ web_server_port }} default_server;
root {{ web_server_root }};
index {{ web_server_index }};

location / {
try_files $uri $uri/ =404;
}
}
  1. Define a handler in handlers/main.yml:
yaml
---
- name: Restart nginx
service:
name: nginx
state: restarted
become: true

Publishing Your Role to Ansible Galaxy

Once you've created and tested your role, you can share it with the community:

  1. Create a GitHub Repository: Push your role to a GitHub repository.

  2. Create an Ansible Galaxy Account: Sign up at galaxy.ansible.com.

  3. Import Your Role:

    • Log in to Galaxy
    • Click on "My Content" -> "Add Content"
    • Select the GitHub repository containing your role

Your role will be available for others to install using:

bash
ansible-galaxy install yourusername.yourrole

Versioning Your Role

It's a good practice to tag releases of your role:

bash
git tag -a v1.0.0 -m "First stable release"
git push --tags

Users can then install specific versions:

bash
ansible-galaxy install yourusername.yourrole,v1.0.0

Ansible Galaxy Collections

In addition to roles, Ansible Galaxy also supports Collections, which are a distribution format for Ansible content that can include playbooks, roles, modules, and plugins.

Installing a Collection

bash
ansible-galaxy collection install community.general

Using a Collection in Your Playbook

yaml
---
- hosts: all
collections:
- community.general
tasks:
- name: Use a module from the collection
archive:
path: /path/to/file.txt
dest: /path/to/file.tar.gz
format: gz

Advanced Galaxy Usage

Role Dependencies

You can define dependencies for your role in the meta/main.yml file:

yaml
dependencies:
- role: geerlingguy.nginx
version: 3.0.0
- role: geerlingguy.mysql
version: 3.3.0

These dependencies will be automatically installed when someone installs your role.

Offline Installation

For environments without internet access, you can download roles and install them offline:

bash
# On a machine with internet access:
ansible-galaxy role install geerlingguy.nginx --ignore-certs -p ./roles --force

# Copy the roles directory to the offline machine
# Then on the offline machine:
ansible-galaxy install -r requirements.yml -p /path/to/roles --offline

Best Practices for Ansible Galaxy Roles

  1. Documentation: Provide clear documentation in your README.md
  2. Idempotency: Ensure your role tasks are idempotent (can be run multiple times without changing the result beyond the first run)
  3. Variable Naming: Use a prefix for your variables to avoid conflicts
  4. Testing: Include tests for your role
  5. Molecule: Consider using Molecule for testing your roles
  6. Tagging: Tag your GitHub releases
  7. CI/CD: Set up CI/CD for your role

Troubleshooting Common Issues

Role Not Found

If you get a "Role not found" error:

  • Check the role name and spelling
  • Ensure you have internet connectivity
  • Try specifying the exact version
bash
ansible-galaxy install geerlingguy.nginx,3.0.0

Permission Denied

If you get permission errors:

  • Check that you have write permissions to the roles directory
  • Use --roles-path to install to a different location
  • Use sudo if necessary (but be careful with this approach)

API Rate Limiting

If you hit rate limits with the Galaxy API:

  • Use authentication with a token
  • Space out your requests
  • Install roles from a requirements file instead of individually

Summary

Ansible Galaxy is a powerful tool that helps you find, reuse, and share Ansible roles. It promotes code reuse and standardization across the Ansible community.

In this tutorial, we've covered:

  • What Ansible Galaxy is and how it benefits your automation workflow
  • How to find and install roles from Galaxy
  • How to use Galaxy roles in your playbooks
  • Creating your own custom roles
  • Publishing your roles to Galaxy
  • Working with collections
  • Advanced usage and best practices

Additional Resources

Exercises

  1. Search for and install a role that helps manage users on a system.
  2. Create a playbook that uses at least two Galaxy roles together.
  3. Initialize a new role for installing and configuring your favorite application.
  4. Add variables to your role to make it configurable.
  5. Create a small test environment and test your role with different variable values.
  6. Add proper documentation to your role's README.md.
  7. (Advanced) Set up Molecule testing for your role.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)