Intro
When it comes to infrastructure automation, Ansible stands out as one of the most popular and powerful tools today. At the heart of Ansible’s automation capabilities are its modules, which serve as the primary building blocks for defining tasks and actions in your Ansible playbooks and roles. In this post, we’re going to dive into the opportunity-rich world of Ansible modules, focusing here on the foundational ansible.builtin
collection, which is where every Ansible user should likely start when they’re looking for ways to bring new automation features and functionality to your infrastructure.
This post expands on Level Up’s previous coverage of “Your First 10 Ansible Modules“.
What Are Ansible Modules, Anyway?
In Ansible, modules are ultimately just small, self-contained scripts or programs that carry out specific tasks for you, usually (but certainly not always!) on remote hosts. These tasks can range from simple operations like creating directories or managing files… to more complex actions like configuring provisioning hosts or orchestrating application deployments. Modules abstract the underlying system-specific details and provide a consistent and reliable way to manage different aspects of your infrastructure. If we think of hosts as being the “nouns” of Ansible, then modules are basically the “verbs”, and we can mix and match modules to achieve just about any imaginable automation workflow in modern computing environments.
RELATED CONTENT: Level Up’s YouTube playlist on using Red Hat® Ansible Automation Platform (AAP) for Linux Configuration Management
Understanding Ansible Builtin Modules
Ansible helpfully comes with a deep collection of builtin modules that cover a pretty wide range of use cases. As you’ll see below, these modules are quite capable of doing a lot of the heavy-lifting in your Day 1 and Everyday Linux configuration management automations (and yes, there are equivalents for many/most of these in the ansible.windows
collection). We’ve grouped them into 10 fairly logical categories (there’s admittedly some overlap in categories in practice), picked some worth calling out in each category, and put a spotlight 5 modules in particular in the more intermediate/advanced end of the spectrum– all to give you some fast ideas on how you can start getting the most out of what’s already included in Ansible, right now, today!
Inventory Management:
ping module
– Try to connect to host, verify a usable python and return pong on successgroup_by module
– Create Ansible groups based on factsadd_host
module – Add a host (and alternatively a group) to the ansible-playbook in-memory inventory. Super helpful for provisioning situations. Here’s a playbook sketch:
---
- name: Provision and Configure RHEL EC2 Instance
hosts: localhost
gather_facts: false
collections:
- amazon.aws
tasks:
- name: Create RHEL EC2 instance
amazon.aws.ec2_instance:
instance_type: t2.micro
image_id: ami-XXXXXXXXXXXXXXXXX
region: us-east-1
key_name: your-key-pair
count: 1
state: present
wait: yes
register: ec2_instance
- name: Add the new instance to the inventory
ansible.builtin.add_host:
name: "{{ ec2_instance.instances[0].private_ip }}"
ansible_ssh_user: ec2-user
ansible_ssh_private_key_file: /path/to/your/key.pem
ansible_python_interpreter: /usr/bin/python3
when: ec2_instance.changed
- name: Configure /etc/motd on the new instance
hosts: ec2_instances
tasks:
- name: Set custom message in /etc/motd
ansible.builtin.template:
src: motd.j2
dest: /etc/motd
become: true
Package Management:
apt module
– Manages apt-packagesdnf module
– Manages packages with the dnf package managerpackage module
– Generic OS package manageryum module
– Manages packages with the yum package manageryum_repository module
– Add or remove YUM repositories. Fairly common in orgs which may use non-Red Hat mirrors, etc. Here’s a playbook sketch:
---
- name: Manage YUM Repositories
hosts: all
become: true
tasks:
- name: Add a new YUM repository
ansible.builtin.yum_repository:
name: example_repo
description: Example Repository
baseurl: http://example.com/repo
gpgcheck: yes
gpgkey: http://example.com/repo/RPM-GPG-KEY
enabled: yes
notify:
- Refresh YUM cache
- name: Remove an existing YUM repository
ansible.builtin.yum_repository:
name: old_repo
state: absent
notify:
- Refresh YUM cache
handlers:
- name: Refresh YUM cache
ansible.builtin.command: yum clean all
File and Configuration Management:
blockinfile module
– Insert/update/remove a text block surrounded by marker linescopy module
– Copy files to remote locationsfile module
– Manage files and file propertiestemplate module
– Template a file out to a target hostfetch module
– Fetch files from remote nodes. Because sometimes you need to pull files back for further processing, historical reporting, etc. Here’s a playbook sketch:
---
- name: Fetch httpd.conf from Apache Hosts
hosts: web
tasks:
- name: Fetch httpd.conf from remote host
ansible.builtin.fetch:
src: /etc/httpd/conf/httpd.conf
dest: /tmp/ # Will be saved to /tmp/host1//etc/httpd/conf/httpd.conf
validate_checksum: true
Task Execution and Control:
command module
– Execute simple commands on targets. Cannot handle pipelines or redirects.raw module
– Bypasses SSH to run commandsscript module
– Runs a local script on a remote node after transferring itshell module
– Execute shell commands on targets. CAN handle pipelines and redirects.fail module
– Fail with custom message. Makes an Ansible playbook fail when a condition is met. Here’s a playbook sketch:
---
- name: Check Website Response Code
hosts: localhost
tasks:
- name: Curl the website
ansible.builtin.command: "curl -I -s https://example.com"
register: curl_output
ignore_errors: yes # Ignore non-zero exit codes
- name: Print curl output
ansible.builtin.debug:
var: curl_output.stdout
- name: Check response code
ansible.builtin.fail:
msg: "The website returned a 500 Internal Server Error."
when: "'HTTP/2 500' in curl_output.stdout"
User and Group Management:
group module
– Add or remove groupsuser module
– Manage user accounts
System and Configuration Management:
gather_facts module
– Gathers facts about remote hostshostname module
– Manage hostnameknown_hosts module
– Add or remove a host from the known_hosts filesetup module
– Gathers facts about remote hostssystemd_service module
– Manage systemd units
Role and Playbook Execution:
import_playbook module
– Import a playbookimport_tasks module
– Import a task listinclude_role module
– Load and execute a roleinclude_tasks module
– Dynamically include a task listinclude_vars module
– Load variables from files, dynamically within a task
Web and Network Services:
get_url module
– Downloads files from HTTP, HTTPS, or FTP to nodeuri module
– Interacts with webservices
Service and Process Management:
service module
– Manage servicesservice_facts module
– Return service state information as fact datareboot module
– Reboot a machine. Here’s a playbook sketch:
---
- name: Patch and Reboot RHEL Hosts
hosts: all
become: true
tasks:
- name: Update packages via dnf
ansible.builtin.dnf:
name: '*'
state: latest
when: ansible_os_family == 'RedHat'
- name: Reboot the system
ansible.builtin.reboot:
reboot_timeout: 300
when: ansible_os_family == 'RedHat'
Version Control and Repository Management:
git module
– Deploy software (or files) from git checkoutssubversion module
– Deploys a subversion repositoryrpm_key module
– Adds or removes a gpg key from the rpm db
Commonly Used Module Parameters
Pro tip! Every Ansible module comes with specific parameters that allow you to customize its behavior. Here are some parameters you’ll frequently encounter when you’re using Ansible modules:
name
: A human-readable name for the task.state
: Defines the desired state of the resource (e.g.,present
,absent
,started
,stopped
).src
anddest
: Paths to source and destination files or directories.vars
: Variables to pass to the module.with_items
orloop
: Iterate over a list of items.register
: Store the result of a task for later use.when
: Apply a task conditionally based on a specified condition.
Ansible Galaxy and Red Hat Certified Collections
In addition to built-in modules, Ansible has a vast ecosystem of community-contributed modules available on Ansible Galaxy. Red Hat® also hosts Certified Content for Ansible Automation Platform® for AAP customers (both of which will be the subjects of future posts). These content hubs bring you modules which can dramatically extend Ansible’s functionality for you, covering the broadest possible spectrum of applications and systems.
Conclusion
Ansible modules are basically the propellers of the aircraft carrier that is Red Hat’s Ansible Automation Platform, providing a powerful and flexible way to manage and automate various aspects of your IT infrastructure. By understanding the essential built-in modules and their parameters, you’re now well-equipped to begin tackling a wide range of automation tasks in your organization.
As you dig deeper into Ansible, be sure to remember to explore community-contributed modules and keep up with the ever-evolving Ansible ecosystem. Armed with these resources, you’ll be on your way to becoming an Ansible automation expert.
In upcoming blog posts, we’ll be exploring a variety of Ansible topics, including custom modules, more on playbooks and roles, as well as best practices for managing complex infrastructure and applications. Stay tuned for more insights into the world of Ansible automation!