Hi there! I'm Shrijith Venkatrama, founder of Hexmos. Right now, I’m building LiveAPI, a first of its kind tool for helping you automatically index API endpoints across all your repositories. LiveAPI helps you discover, understand and use APIs in large tech infrastructures with ease.
Ansible is a game-changer for automating server setups. It’s simple, agentless, and lets you define infrastructure as code using YAML. But the real power lies in its modules—pre-built units of work that handle everything from installing packages to configuring databases. With thousands of modules available, knowing which ones are the most valuable can save you time and headaches. This post dives into the most practical Ansible modules for automating server setups, with examples you can actually use. Let’s get to it.
Why Ansible Modules Matter
Modules are the building blocks of Ansible playbooks. Each module is designed for a specific task, like managing files, installing software, or restarting services. Instead of writing complex shell scripts, you use modules to do the heavy lifting. The trick is picking the right ones for common server setup tasks. Below, I’ll cover 7 essential modules, explain how they work, and show you real-world examples. These are the ones I lean on for most server automation tasks—battle-tested and reliable.
1. Package Management with package
and apt
/yum
Managing software packages is a core part of server setup. The package
module is your go-to for installing software across different Linux distributions (Debian, CentOS, etc.) without worrying about the underlying package manager. For more control on specific systems, use apt
(Debian/Ubuntu) or yum
(RHEL/CentOS).
-
Why it’s valuable: The
package
module abstracts away differences betweenapt
andyum
, making playbooks portable. Useapt
oryum
when you need fine-grained control, like managing repositories. -
Example: Install Nginx on any Linux distro using
package
, and useapt
for a specific Ubuntu setup.
- name: Install Nginx using package module
package:
name: nginx
state: present
become: yes
# Output: Installs nginx package if not already installed
- name: Install Nginx on Ubuntu with apt
apt:
name: nginx
state: latest
update_cache: yes
become: yes
# Output: Updates apt cache and installs latest nginx version
-
Tip: Always use
become: yes
for tasks requiring sudo. Check the Ansible package module docs for more options.
2. File Management with file
The file
module handles creating, modifying, or deleting files and directories. It’s essential for setting up directory structures, managing permissions, or creating empty configuration files.
- Why it’s valuable: Precise control over file attributes like ownership, permissions, and symlinks. It’s simple but powerful for ensuring consistent server environments.
- Example: Create a directory for a web app and set permissions.
- name: Create web app directory
file:
path: /var/www/myapp
state: directory
owner: www-data
group: www-data
mode: '0755'
become: yes
# Output: Creates /var/www/myapp with www-data ownership and 755 permissions
-
Tip: Use
state: absent
to delete files or directories. See the Ansible file module docs for advanced options like recursive permissions.
3. Copying Files with copy
The copy
module transfers files from your local machine (or control node) to the target server. It’s perfect for deploying configuration files, scripts, or static assets.
- Why it’s valuable: Handles file transfers with built-in checksum validation and permission management. It’s idempotent, so it only copies files when needed.
- Example: Deploy a custom Nginx config file.
- name: Copy Nginx config
copy:
src: ./files/nginx.conf
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
become: yes
# Output: Copies nginx.conf to /etc/nginx/nginx.conf, sets permissions
-
Tip: Store source files in a
files/
directory relative to your playbook. Check the Ansible copy module docs for backup options.
4. Managing Services with service
The service
module controls system services (e.g., starting, stopping, or enabling services like Nginx or PostgreSQL). It works across different init systems (systemd, SysVinit).
- Why it’s valuable: Simplifies service management without writing shell commands. It ensures services are in the desired state (running, stopped, enabled on boot).
- Example: Ensure Nginx is running and enabled on boot.
- name: Start and enable Nginx
service:
name: nginx
state: started
enabled: yes
become: yes
# Output: Starts nginx service and enables it to run on boot
-
Tip: Use
state: restarted
to reload configurations. See the Ansible service module docs for more states.
5. User and Group Management with user
The user
module creates, modifies, or deletes user accounts and manages their properties (e.g., home directories, shells, or SSH keys). It’s critical for setting up secure server access.
- Why it’s valuable: Automates user setup, ensuring consistent account configurations across servers.
- Example: Create a deploy user with an SSH key.
- name: Create deploy user
user:
name: deploy
state: present
shell: /bin/bash
home: /home/deploy
create_home: yes
become: yes
# Output: Creates deploy user with home directory /home/deploy
- name: Add SSH key for deploy user
authorized_key:
user: deploy
state: present
key: "{{ lookup('file', './files/deploy_key.pub') }}"
become: yes
# Output: Adds SSH public key to /home/deploy/.ssh/authorized_keys
-
Tip: Pair with the
authorized_key
module for SSH access. Check the Ansible user module docs for password management.
6. Template Rendering with template
The template
module generates dynamic configuration files using Jinja2 templates. It’s perfect for customizing configs based on variables (e.g., IP addresses, ports).
-
Why it’s valuable: Enables dynamic, reusable configurations without hardcoding values. It’s a step up from the
copy
module for complex setups. - Example: Deploy a templated Nginx config with a dynamic server name.
- name: Deploy templated Nginx config
template:
src: ./templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
become: yes
# Output: Renders nginx.conf.j2 to /etc/nginx/nginx.conf with variables replaced
Template file (templates/nginx.conf.j2):
server {
listen 80;
server_name {{ server_name }};
root /var/www/html;
}
-
Tip: Store templates in a
templates/
directory. See the Ansible template module docs for variable handling.
7. Running Commands with command
and shell
The command
and shell
modules execute arbitrary commands on the target server. Use command
for simple, non-pipelined commands and shell
when you need pipes, redirects, or environment variables.
- Why it’s valuable: Fills gaps when no specific module exists for a task. Use sparingly to keep playbooks idempotent.
- Example: Check disk space and log it.
- name: Check disk space
command: df -h
register: disk_space
# Output: Stores disk space output in disk_space.stdout
- name: Log disk space to file
shell: echo "{{ disk_space.stdout }}" >> /var/log/disk_usage.log
become: yes
# Output: Appends df -h output to /var/log/disk_usage.log
-
Tip: Use
register
to capture output. Check the Ansible command module docs for safety tips.
8. Managing Databases with postgresql_db
and mysql_db
For database servers, the postgresql_db
and mysql_db
modules handle database creation and management. They’re essential for setting up apps that rely on PostgreSQL or MySQL.
- Why it’s valuable: Automates database setup without manual SQL commands. Works seamlessly with user and privilege management modules.
- Example: Create a PostgreSQL database for a web app.
- name: Install PostgreSQL client
package:
name: python3-psycopg2
state: present
become: yes
# Output: Installs psycopg2 for PostgreSQL connectivity
- name: Create app database
postgresql_db:
name: myapp_db
state: present
become: yes
become_user: postgres
# Output: Creates myapp_db database
-
Tip: Ensure the database client (e.g.,
psycopg2
) is installed. See the Ansible postgresql_db module docs for advanced options.
Putting It All Together: A Sample Playbook
Here’s a complete playbook combining several modules to set up a basic web server with Nginx and a PostgreSQL database.
- name: Set up web server and database
hosts: webservers
become: yes
vars:
server_name: example.com
tasks:
- name: Install Nginx
package:
name: nginx
state: present
- name: Create web app directory
file:
path: /var/www/myapp
state: directory
owner: www-data
group: www-data
mode: '0755'
- name: Deploy Nginx config
template:
src: ./templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
notify: Restart Nginx
- name: Start and enable Nginx
service:
name: nginx
state: started
enabled: yes
- name: Install PostgreSQL client
package:
name: python3-psycopg2
state: present
- name: Create app database
postgresql_db:
name: myapp_db
state: present
become_user: postgres
handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted
- What it does: Installs Nginx, sets up a web directory, deploys a templated config, starts Nginx, and creates a PostgreSQL database.
- Output: A fully configured web server ready to serve content with a database backend.
Next Steps for Mastering Ansible Modules
These modules—package
, file
, copy
, service
, user
, template
, command
/shell
, and postgresql_db
/mysql_db
—cover most server setup tasks. To go deeper, explore Ansible Galaxy for community modules or write custom ones for niche tasks. Experiment with these in a test environment (use Vagrant or Docker for quick setups). The key is to start small, test often, and keep playbooks modular. Check the Ansible documentation for more modules and best practices. With these tools, you’ll be automating servers like a pro in no time.
Top comments (0)