Creating Galaxy Roles in Ansible
Introduction
Ansible Galaxy is a hub for finding, reusing, and sharing Ansible roles. Roles are a way of bundling automation content and can be reused across different projects. In this tutorial, we will walk through the process of creating and using roles in Ansible Galaxy.
Prerequisites
Before we start, make sure you have the following installed on your system:
- Ansible (version 2.9 or later)
- Python (version 2.7 or later)
Step 1: Install Ansible
If you haven't installed Ansible yet, you can do so using pip. Open your terminal and run the following command:
To verify the installation, run:
config file = /etc/ansible/ansible.cfg
configured module search path = ['/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.7/dist-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.5 (default, Nov 7 2019, 10:50:52) [GCC 8.3.0]
Step 2: Create a New Role
Use the ansible-galaxy
command to create a new role. Navigate to your project directory and run:
This command will create a new role directory structure:
├── README.md
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml
Step 3: Define Tasks
Edit the tasks/main.yml
file to define the tasks for your role. Here is an example of a simple task that installs a package:
--- - name: Install nginx apt: name: nginx state: present
Step 4: Define Default Variables
Edit the defaults/main.yml
file to define default variables for your role. Here is an example:
--- package_name: nginx
Step 5: Use the Role in a Playbook
Create a playbook to use your new role. Here is an example site.yml
playbook:
--- - hosts: webservers roles: - my_role
Run the playbook using the ansible-playbook
command:
Conclusion
In this tutorial, we walked through the process of creating a new role in Ansible Galaxy, defining tasks and variables, and using the role in a playbook. By following these steps, you can create reusable and shareable automation content for your projects.