Operations 22 min read

Master the 20 Most Used Ansible Modules: Practical Tips and Pitfall Avoidance

This article walks you through the twenty most frequently used Ansible modules, explaining their purpose, key parameters, real‑world examples, common mistakes, and best‑practice recommendations so you can automate tasks reliably and avoid typical pitfalls.

AI Agent Super App
AI Agent Super App
AI Agent Super App
Master the 20 Most Used Ansible Modules: Practical Tips and Pitfall Avoidance

Why focus on a handful of modules

Although Ansible ships with over 3000 modules, the author finds that only about twenty are used daily in real‑world operations. Mastering these core modules gives you the most bang for your buck and keeps playbooks simple and idempotent.

Command‑execution class

command runs a command without a shell, so it cannot use pipes, variable expansion, or redirection. Common parameters are cmd, chdir, creates, and removes. Example:

---
- name: Check disk usage
  ansible.builtin.command:
    cmd: df -h /
    chdir: /tmp
    register: disk_result
- name: Show disk info
  ansible.builtin.debug:
    var: disk_result.stdout_lines

Idempotency can be achieved with creates or removes so the task is skipped when the marker file exists.

shell invokes /bin/sh (or a custom executable) and supports pipelines, redirection, and variable substitution. Use it when you need full shell features, but prefer dedicated modules for idempotency.

- name: Find large log files and compress
  ansible.builtin.shell:
    cmd: find /var/log -name "*.log" -size +100M | xargs gzip
    executable: /bin/bash

script copies a local script to the remote host, runs it, and removes it afterwards—ideal for batch deployment scripts.

- name: Run deployment script
  ansible.builtin.script:
    cmd: /opt/scripts/deploy.sh --env prod --version 2.1.0
    executable: /bin/bash
    creates: /opt/app/.deployed_v2.1.0

raw sends raw SSH commands without requiring Python on the target, useful for bootstrapping bare machines.

- name: Install Python on bare metal
  ansible.builtin.raw: apt-get update; apt-get install -y python3
  become: yes

File‑management class

copy transfers a local file or writes literal content to a remote path. Parameters include src, content, dest, owner, group, mode, and backup. Example of copying a config file:

- name: Deploy nginx config
  ansible.builtin.copy:
    src: files/nginx.conf
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: "0644"
    backup: yes

When src ends with a slash, only the directory contents are copied; without the slash the directory itself is copied.

template works like copy but processes a Jinja2 template, allowing variables, loops, and defaults. Example:

- name: Deploy nginx config from template
  ansible.builtin.template:
    src: templates/nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: "0644"
    vars:
      nginx_port: 8080
      nginx_hostname: "www.example.com"

file manages file attributes, creates directories, links, or removes paths. The state option can be file, directory, link, absent, etc.

- name: Create app directory
  ansible.builtin.file:
    path: /opt/myapp/logs
    state: directory
    owner: appuser
    group: appgroup
    mode: "0755"

lineinfile edits a single line identified by a regular expression; it only changes the last matching line.

- name: Enable SSH password auth
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    regexp: "^#?PasswordAuthentication"
    line: "PasswordAuthentication yes"
    state: present

replace performs a global regex substitution, similar to sed.

- name: Change port in all server blocks
  ansible.builtin.replace:
    path: /etc/nginx/sites-enabled/default
    regexp: "(listen )80(; )"
    replace: "\1443\2"

blockinfile inserts or updates a whole block marked by a comment, preventing duplicate insertions.

- name: Add cluster hosts
  ansible.builtin.blockinfile:
    path: /etc/hosts
    block: |
      10.0.0.10  node1.cluster.local
      10.0.0.11  node2.cluster.local
      10.0.0.12  node3.cluster.local
    marker: "# {mark} ANSIBLE MANAGED CLUSTER BLOCK"
    state: present

get_url downloads files over HTTP/HTTPS/FTP with optional checksum verification and authentication.

- name: Download JDK
  ansible.builtin.get_url:
    url: "https://example.com/jdk-17.0.2_linux-x64_bin.tar.gz"
    dest: /opt/jdk-17.0.2.tar.gz
    checksum: "sha256:https://example.com/jdk-17.0.2.sha256"
    mode: "0644"
    timeout: 120

Package‑management class

yum/dnf manages RPM packages on RHEL/CentOS. Examples include installing a single package, batch installing a list, specifying a version, updating all packages, and removing a package.

- name: Install nginx
  ansible.builtin.yum:
    name: nginx
    state: present

apt does the same for Debian/Ubuntu, with options like update_cache and cache_valid_time to reduce unnecessary updates.

- name: Update apt cache and install nginx
  ansible.builtin.apt:
    name: nginx
    state: present
    update_cache: yes
    cache_valid_time: 3600

pip installs Python packages, optionally inside a virtual environment.

- name: Install Python dependencies in venv
  ansible.builtin.pip:
    name:
      - flask
      - gunicorn
    virtualenv: /opt/myapp/venv
    virtualenv_python: python3.10

Service‑management class

service is a generic service manager that works across init systems. Use state: started , stopped , restarted , or reloaded as needed.

- name: Ensure nginx is running and enabled
  ansible.builtin.service:
    name: nginx
    state: started
    enabled: yes

systemd adds systemd‑specific capabilities such as daemon_reload , masked , and target management. Choose systemd when you need those extra features.

- name: Deploy and enable custom service
  ansible.builtin.systemd:
    name: myapp
    state: started
    enabled: yes
    daemon_reload: yes

User‑management class

user creates, modifies, or removes system accounts. Parameters include name , comment , shell , groups , password , and generate_ssh_key .

- name: Create application user
  ansible.builtin.user:
    name: appuser
    comment: "Application Service Account"
    shell: /bin/bash
    groups: docker,appgroup
    append: yes
    create_home: yes
    state: present

group manages groups, typically used together with user .

- name: Create appgroup
  ansible.builtin.group:
    name: appgroup
    gid: 2000
    state: present

Scheduled‑task class

cron adds, disables, or removes crontab entries. The name parameter acts as a comment that Ansible uses to locate the entry later.

- name: Daily backup at 2:30 AM
  ansible.builtin.cron:
    name: "Daily database backup"
    minute: "30"
    hour: "2"
    job: "/opt/scripts/db_backup.sh > /var/log/backup.log 2>&1"
    user: root
    state: present

System‑information & debugging class

setup gathers facts about the remote host (OS, kernel, CPU, memory, IP, etc.) that can be used as variables in playbooks.

# Show all facts
ansible all -m setup
# Filter specific fact
ansible all -m setup -a "filter=ansible_distribution"

debug prints variables or custom messages, useful for troubleshooting and conditional warnings.

- name: Show OS info
  ansible.builtin.debug:
    msg: "Running {{ ansible_distribution }} {{ ansible_distribution_version }} on {{ ansible_hostname }}"

Quick‑reference table

Command‑execution: command , shell , script , raw File‑management: copy , template , file , lineinfile , replace , blockinfile , get_url Package‑management: yum/dnf , apt , pip Service‑management: service , systemd User‑management: user , group Other: cron , setup , debug

Conclusion

The key principle is “use the right tool for the job”: prefer dedicated modules for idempotency, fall back to shell only when necessary, and keep playbooks concise. Mastering these twenty modules covers more than ninety percent of everyday automation scenarios; the next article will explore how to structure roles for reusable playbooks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

automationconfiguration-managementDevOpsyamlansibleplaybook
AI Agent Super App
Written by

AI Agent Super App

AI agent applications, installation, large-model testing, computer fundamentals, IT operations and maintenance exchange, network technology exchange, Linux learning

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.