Working with Common Modules
1. Managing Files
| Module | Parameters | Description | Example |
|---|---|---|---|
| ansible.builtin.copy | src, dest, content |
Copies a file from the local machine to the remote host. | |
| ansible.builtin.fetch | src, dest |
Fetches a file from the remote host to the local machine. | |
| ansible.builtin.file | path, state, mode |
Changes the attributes of files or directories. | |
| ansible.builtin.template | src, dest, vars |
Renders a template file using Jinja2 and copies it to the remote host. | |
Example: Copying a file
- name: Copy a file from local to remote
ansible.builtin.copy:
src: /local/config.json
dest: /etc/app/config.json
mode: '0644'
Example: Fetching a file from remote
- name: Fetch a log file from remote
ansible.builtin.fetch:
src: /var/log/app.log
dest: ./logs/app.log
Example: Setting file permissions
- name: Set file permissions
ansible.builtin.file:
path: /etc/app/config.json
mode: '0600'
2. Executing Commands
| Parameter | Description | Example |
|---|---|---|
| cmd | Command to execute (required) | ls -l |
| chdir | Change to this directory before executing the command | /home/user |
| creates | Only run if this file does not exist | /tmp/lockfile |
| removes | Only run if this file exists | /tmp/oldfile |
| warn | Whether to warn if the command is not found | false |
Example: Basic command execution
- name: List files in directory
command: ls -l
args:
chdir: /home/user
Example: Conditional command execution
- name: Create lock file only if it doesn't exist
command: touch /tmp/lockfile
args:
creates: /tmp/lockfile
Note: The
command module does not support shell operators like pipes or redirections. Use the shell module for such cases.
3. Managing Packages
| Module | Description | Example |
|---|---|---|
| ansible.builtin.yum | Manages packages on RHEL/CentOS/Fedora systems using YUM | |
| ansible.builtin.apt | Manages packages on Debian/Ubuntu systems using APT | |
| ansible.builtin.package | Generic package manager module that detects the OS and uses the appropriate backend (yum, apt, etc.) | |
Note: The
ansible.builtin.package module is useful for writing cross-platform playbooks, but it's less specific and might not support all advanced features of the OS-specific modules.4. Managing Services
| Parameter | Description | Default | Notes |
|---|---|---|---|
| name | Name of the service to manage | Required | |
| state | State of the service | running |
Valid values: running, stopped, restarted, reloaded |
| enabled | Whether the service should be enabled at boot | false |
Boolean |
| pattern | Pattern to match service name (used for systemd) | null |
Only used with systemd |
Example: Start and Enable a Service
- name: Start and enable nginx service
ansible.builtin.systemd:
name: nginx
state: started
enabled: true
Example: Stop and Disable a Service
- name: Stop and disable mysql service
ansible.builtin.systemd:
name: mysql
state: stopped
enabled: false
Note: The
systemd module is preferred over the older service module for systems using systemd.
Warning: Ensure the service name matches exactly as recognized by the system. Incorrect names can lead to silent failures.
5. Managing Users
| Parameter | Description | Default | Notes |
|---|---|---|---|
| name | User name to manage | Required | |
| state | Whether the user should exist or not | present |
|
| password | Hashed password for the user | None |
Use ansible.builtin.set_fact to hash before using |
| uid | User ID to assign | None |
|
| group | Primary group for the user | None |
|
| groups | Additional groups for the user | None |
Comma-separated list |
| shell | Shell to assign to the user | /bin/bash |
|
| home | Home directory path | /home/{{ name }} |
|
| createhome | Whether to create home directory | true |
|
| system | Whether to create a system user | false |
Example: Create a user with specific group and shell
- name: Create a user named john
ansible.builtin.user:
name: john
state: present
group: developers
shell: /bin/zsh
createhome: true
Example: Remove a user
- name: Remove a user named john
ansible.builtin.user:
name: john
state: absent
Note: The
password parameter requires a hashed value. You can use ansible.builtin.command or ansible.builtin.shell to hash the password using tools like openssl passwd -1.
6. Working with Git
| Parameter | Description | Default | Notes |
|---|---|---|---|
| repo | Git repository URL or path | Required | |
| dest | Destination directory to clone into | Required | |
| version | Branch, tag, or commit to checkout | HEAD | |
| accept_hostkey | Accept host key without prompting | false | Use with caution |
| force | Force overwrite of existing directory | false | |
| update | Update existing repository | true |
Example: Clone a Git Repository
- name: Clone a Git repository
git:
repo: https://github.com/example/myapp.git
dest: /opt/myapp
version: main
Example: Clone with Specific Branch and Force Update
- name: Clone with specific branch
git:
repo: https://github.com/example/myapp.git
dest: /opt/myapp
version: feature/new-feature
force: true
update: true
Note: The
git module supports SSH keys and HTTPS authentication via environment variables or inline credentials.
Warning: Using
force: true will delete and re-clone the repository, potentially losing local changes.
7. Managing Archives
| Parameter | Description | Default | Notes |
|---|---|---|---|
| archive | Path to the archive file to create or extract | None | Required for archive state |
| dest | Destination directory or file path for extraction | None | Required for extract state |
| format | Archive format (zip, tar, gz, bz2) | None | Must be specified for archive state |
| remote_src | Whether the archive is located on the remote host | false | Useful for extracting archives already present on the target |
| exclude | List of files or patterns to exclude from the archive | None | Supports glob patterns |
Example: Create a tar.gz archive
- name: Create a tar.gz archive
ansible.builtin.archive:
path: /etc
dest: /tmp/etc.tar.gz
format: gz
Example: Extract an archive to a directory
- name: Extract archive to directory
ansible.builtin.unarchive:
src: /tmp/etc.tar.gz
dest: /tmp/extracted
remote_src: yes
Note: The
archive module creates compressed archives, while unarchive extracts them. Both modules support various formats including tar, zip, and gzip.
8. Checking File Stats
| Parameter | Description | Default |
|---|---|---|
| path | Path to the file or directory to check | Required |
| get_checksum | Whether to calculate and return the checksum of the file | false |
| get_md5 | Whether to calculate and return the MD5 hash of the file | false |
| get_sha1 | Whether to calculate and return the SHA1 hash of the file | false |
| get_sha256 | Whether to calculate and return the SHA256 hash of the file | false |
Example: Check file stats
- name: Check file stats
stat:
path: /etc/passwd
get_checksum: true
get_md5: true
register: file_stats
- name: Display file stats
debug:
msg: "File size: {{ file_stats.stat.size }} bytes, MD5: {{ file_stats.stat.md5 }}"
9. Setting Variables
| Property | Description | Values | Notes |
|---|---|---|---|
| ansible_facts | Variables that are automatically gathered by Ansible about the target host | dict |
Read-only, populated by setup module |
| hostvars | Variables that are specific to a particular host | dict |
Available in playbooks and templates |
| groupvars | Variables that are specific to a group of hosts | dict |
Loaded from group_vars/ directory |
| hostvars | Variables that are specific to a particular host | dict |
Available in playbooks and templates |
Example: Setting Variables in Playbook
- name: Set variables in playbook
hosts: all
vars:
app_port: 8080
app_host: "localhost"
tasks:
- name: Display variables
debug:
msg: "App is running on {{ app_host }}:{{ app_port }}"
Example: Using set_fact Module
- name: Set runtime facts
hosts: webservers
tasks:
- name: Set a fact from command output
set_fact:
server_uptime: "{{ ansible_facts.uptime }}"
- name: Use the fact in a task
debug:
msg: "Server has been up for {{ server_uptime }}"
Note: Variables set with
set_fact are available for the remainder of the playbook run, but not persisted to disk or across multiple playbook runs.
10. Managing Cron Jobs
| Parameter | Description | Default | Notes |
|---|---|---|---|
| name | The name of the cron job | Required | |
| job | The command to run | Required | |
| state | Whether the job should be present or absent | present |
|
| minute | Minute(s) to run the job | * |
Can be a list or single value |
| hour | Hour(s) to run the job | * |
Can be a list or single value |
| day | Day(s) to run the job | * |
Can be a list or single value |
| month | Month(s) to run the job | * |
Can be a list or single value |
| weekday | Weekday(s) to run the job | * |
Can be a list or single value |
| user | User context to run the job as | root |
|
| cron_file | File to manage cron jobs in | /etc/crontab |
Used when managing system crontabs |
Example: Create a Cron Job
- name: Create a cron job to backup logs
ansible.builtin.cron:
name: "Log Backup"
minute: "0"
hour: "2"
job: "/usr/bin/backup-logs.sh"
user: "root"
Example: Remove a Cron Job
- name: Remove a cron job
ansible.builtin.cron:
name: "Log Backup"
state: "absent"
Note: Cron jobs managed by Ansible are identified by their
name. If you change the name, a new job will be created and the old one will remain.
11. Pausing Execution
| Parameter | Description | Default |
|---|---|---|
| sleep | Number of seconds to pause | 0 |
| pause | Alias for sleep |
Example: Pause for 5 seconds
- name: Pause execution for 5 seconds
ansible.builtin.wait_for:
delay: 5
Example: Pause with custom message
- name: Wait before continuing
ansible.builtin.wait_for:
delay: 10
msg: "Waiting for 10 seconds before proceeding"
12. Asserting Conditions
| Parameter | Description | Default | Notes |
|---|---|---|---|
| assert | Condition to evaluate | Required | Must be a valid Jinja2 expression |
| fail_msg | Message to display if assertion fails | Error message from assert | Customize failure message |
| success_msg | Message to display if assertion passes | Success message from assert | Optional custom success message |
| quiet | Suppress output when assertion passes | false | Set to true to suppress success messages |
Example: Basic Assertion
- name: Check if system is running Ubuntu
assert:
that:
- ansible_distribution == "Ubuntu"
fail_msg: "This playbook requires Ubuntu"
success_msg: "System is Ubuntu"
Example: Complex Assertion with Variables
- name: Validate application configuration
assert:
that:
- app_port is defined
- app_port > 0
- app_port < 65536
fail_msg: "Invalid port number in app configuration"
Note: The
assert module is useful for validating conditions during playbook execution. It can be used to ensure that preconditions are met before proceeding with tasks.