Operations 41 min read

Master Ansible: Essential Commands and Common Modules Explained

This guide provides a comprehensive overview of Ansible's ad‑hoc command options and the most frequently used modules—including shell, copy, template, file, fetch, synchronize, yum, service, user, and cron—detailing their parameters, usage examples, and best‑practice tips for efficient automation.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Ansible: Essential Commands and Common Modules Explained

1.1 Ansible Command Explanation

Tasks executed with the ansible command are called ad‑hoc commands, which differ from playbooks. Ad‑hoc commands are typically used for batch management, while playbooks provide full automation.

Common options: -a MODULE_ARGS / --args=MODULE_ARGS: Pass arguments to a module. --ask-vault-pass: Prompt for the vault password. -B SECONDS / --background=SECONDS: Run the task asynchronously and kill it after the specified timeout. Default is synchronous (blocking). -P POLL_INTERVAL / --poll=POLL_INTERVAL: Interval (seconds) for polling in async mode, default 10 s. -C / --check: Perform a dry‑run to predict changes without applying them. -D / --diff: Show differences when a file or template changes; works well with -C. -e EXTRA_VARS / --extra-vars=EXTRA_VARS: Provide extra variables (key=value or YAML/JSON). -f FORKS / --forks=FORKS: Number of parallel processes (default 5). -h / --help: Show help information. -i INVENTORY / --inventory-file=INVENTORY: Specify inventory file(s), default /etc/ansible/hosts. -l SUBSET / --limit=SUBSET: Further limit the target host list. --list-hosts: List matching hosts without executing anything. -m MODULE_NAME / --module-name=MODULE_NAME: Choose the module to run (default "command"). -M MODULE_PATH / --module-path=MODULE_PATH: Specify a custom module directory. --new-vault-password-file=NEW_VAULT_PASSWORD_FILE: New vault password file for re‑keying. -o / --one-line: Simplify output to a single line. --output=OUTPUT_FILE: Write encrypted/decrypted output to a file (use - for stdout). --syntax-check: Check playbook syntax without execution. -t TREE / --tree=TREE: Record output to the specified directory (useful for slow commands). --vault-password-file=VAULT_PASSWORD_FILE: Specify vault password file. -v / --verbose: Increase verbosity (e.g., -vvv, -vvvv). --version: Show Ansible version.

Connection options: -k / --ask-pass: Prompt for SSH password. --private-key=KEY_FILE / --key-file=KEY_FILE: Use a private key file for SSH authentication. -u REMOTE_USER / --user=REMOTE_USER: Connect as the specified user. -c CONNECTION / --connection=CONNECTION: Connection type (default ssh; options: paramiko, ssh, winrm, local). -T TIMEOUT / --timeout=TIMEOUT: Connection timeout in seconds (default 10). --ssh-common-args=SSH_COMMON_ARGS: Extra arguments passed to ssh / sftp / scp. --sftp-extra-args=SFTP_EXTRA_ARGS: Extra arguments for sftp only. --scp-extra-args=SCP_EXTRA_ARGS: Extra arguments for scp only. --ssh-extra-args=SSH_EXTRA_ARGS: Extra arguments for ssh only.

Privilege escalation options: -s / --sudo: Deprecated; use become instead. -U SUDO_USER / --sudo-user=SUDO_USER: Deprecated; use become_user instead. -S / --su: Deprecated; use become instead. -K / --ask-become-pass: Prompt for the password required by become. -b / --become: Enable privilege escalation. --become-method=BECOME_METHOD: Choose escalation method (e.g., sudo, su, pbrun, etc.). --become-user=BECOME_USER: Target user for escalation (default root).

1.2 Common Modules

Modules can be listed with ansible-doc -l | grep. Detailed usage is shown with ansible-doc -s module_name. Most modules support the state parameter, typically using present (install/create) or absent (remove).

1.2.1 shell and command

The default module is command, which runs commands directly. shell runs commands through /bin/sh, allowing shell operators and variable expansion.

ansible-doc -s shell
- name: Execute commands in nodes.
  action: shell
    chdir      # Change directory before executing.
    creates    # Skip execution if the specified file exists.
    removes    # Skip execution if the specified file does not exist.

Both modules are not idempotent by default; use creates or removes to achieve idempotence when necessary.

1.2.2 copy module

The copy module transfers files from the control node to remote hosts.

ansible-doc -s copy
- name: Copies files to remote locations.
  action: copy
    backup          # Create a timestamped backup of the destination file.
    dest=           # Destination path (absolute; must be a directory if source is a directory).
    content         # Write the given string directly to the remote file (overrides src).
    directory_mode  # When copying recursively, only copy newly created files.
    follow=[yes|no]# Follow symbolic links.
    force=[yes|no] # Overwrite existing files (default yes).
    group           # Set group ownership.
    owner           # Set file owner.
    mode=           # Set permissions (e.g., 0644, u+rwx).
    src=            # Local source file or directory.

Copy checks MD5 by default; with force=yes it overwrites only when content differs.

1.2.3 template module

The template module renders Jinja2 templates and copies the result to the remote host.

ansible-doc -s template
- name: Templates a file out to a remote server.
  action: template
    backup    # Create a timestamped backup.
    dest=     # Destination path.
    force     # Overwrite if yes (default).
    group     # Set group.
    owner     # Set owner.
    mode      # Set permissions.
    src=      # Path to the Jinja2 template on the control node.
    validate  # Command to validate the rendered file before placement.

When configuration files differ greatly between distributions, select the appropriate template using variables, e.g., nginx{{ ansible_distribution_major_version }}.conf.j2.

1.2.4 file module

Manages file and directory attributes, creation, and removal.

ansible-doc -s file
- name: Sets attributes of files.
  action: file
    group       # Set group.
    owner       # Set owner.
    mode        # Set permissions.
    path=       # Target path (alias: dest, name).
    recurse     # Recursively modify attributes (requires state=directory).
    src         # Source for symlink creation.
    state       # directory|file|touch|link|hard|absent.

1.2.5 fetch module

Pulls files from remote hosts to the control node, storing them under a host‑specific directory.

ansible-doc -s fetch
- name: Fetches a file from remote nodes.
  action: fetch
    dest=               # Local directory to store the file.
    fail_on_missing    # Fail if the source file does not exist.
    flat                # Store directly under <code>dest</code> without host sub‑directory.
    src=                # Remote source file (must be a file).
    validate_checksum   # Verify MD5 after transfer.

1.2.6 synchronize module (rsync wrapper)

Provides a simplified interface to rsync for common synchronization tasks.

ansible-doc -s synchronize
- name: A wrapper around rsync to make common tasks quick and easy.
  action: synchronize
    src=        # Source path (local or remote depending on mode).
    dest=       # Destination path.
    mode        # push (default) or pull.
    archive     # Enable archive mode (equivalent to -a).
    times       # Preserve modification times.
    group       # Preserve group.
    owner       # Preserve owner.
    links       # Copy symlinks as symlinks.
    perms       # Preserve permissions.
    recursive   # Recurse into directories.
    compress    # Compress data during transfer.
    delete      # Delete extraneous files from destination.
    checksum    # Use checksum to determine changes (slow).
    rsync_opts  # Additional rsync options (list).

1.2.7 yum module

Manages packages on RPM‑based systems.

ansible-doc -s yum
- name: Manages packages with the `yum` package manager.
  action: yum
    name=          # Package name (optional version).
    state          # present|installed|latest|absent|removed.
    disable_gpg_check
    disablerepo
    enablerepo
    exclude
    update_cache

1.2.8 yum_repository module

Configures YUM repository files.

ansible-doc -s yum_repository
- name: Add or remove YUM repositories.
  action: yum_repository
    name:          # Repository identifier (unique).
    description:   # Human‑readable description.
    baseurl:       # Repository URL.
    mirrorlist:    # Mirror list URL.
    enabled:       # yes/no (default yes).
    gpgcheck:      # Enable GPG signature checking.
    file:          # Filename (defaults to <name>.repo).
    state:         # present|absent (default present).

1.2.9 service module

Manages SysV init services.

ansible-doc -s service
- name: Manage services.
  action: service
    name=          # Service name.
    state          # started|stopped|restarted|reloaded.
    enabled        # Enable at boot (yes/no).

1.2.10 systemd module

Manages systemd services.

ansible-doc -s systemd
- name: Manage services.
  action: systemd
    name=          # Service name (or unit).
    state          # started|stopped|restarted|reloaded.
    enabled        # Enable at boot.
    masked         # Mask the unit.
    daemon_reload  # Reload systemd manager configuration.

1.2.11 user module

Creates, modifies, or removes user accounts.

ansible-doc -s user
- name: Manage user accounts.
  action: user
    name=          # Username.
    password       # Encrypted password string.
    state          # present|absent (default present).
    system         # Create a system user.
    createhome     # Create home directory.
    home=          # Home directory path.
    uid=           # User ID.
    group=         # Primary group.
    groups=        # Supplementary groups.
    shell=         # Login shell.
    update_password # always|on_create.

1.2.12 authorized_key module

Adds or removes SSH authorized keys for a user.

ansible-doc -s authorized_key
- name: Adds or removes an SSH authorized key.
  action: authorized_key
    user=          # Target user.
    key=           # Public key content or URL.
    state          # present|absent.
    path=          # Path to authorized_keys file (default ~/.ssh/authorized_keys).
    manage_dir     # Manage the directory's ownership/permissions.

1.2.13 debug module

Prints custom messages or variable values during playbook execution.

ansible-doc -s debug
- name: Print statements during execution.
  action: debug
    msg        # Custom message.
    var        # Variable name to display.
    verbosity  # Minimum verbosity level to show.

1.2.14 cron module

Manages crontab entries and environment variables.

ansible-doc -s cron
- name: Manage cron.d and crontab entries.
  action: cron
    name=          # Identifier for the job (required for removal).
    job=           # Command to execute.
    minute= hour= day= month= weekday= # Schedule fields (default *).
    special_time   # Shortcut like @reboot, @daily, etc.
    state          # present|absent.
    user=          # Target user (default current).
    cron_file=     # Custom file under /etc/cron.d.
    env            # Set to yes to define an environment variable.
    disabled       # Disable a job without removing it.

1.2.15 archive module

Creates compressed archives on the remote host.

ansible-doc -s archive
- name: Creates a compressed archive of one or more files or trees.
  action: archive
    dest=          # Destination archive file (required unless path is a single file).
    format=        # Compression format (gz, bz2, zip, tar; default gz).
    path=          # File(s) or directory(ies) to archive (supports globs).
    mode=          # Permissions for the archive.
    owner=         # Owner for the archive.
    group=         # Group for the archive.
    remove=        # Delete source files after archiving.

1.2.16 unarchive module

Unpacks archives on the remote host; can copy from control node or operate on a remote file.

ansible-doc -s unarchive
- name: Unpacks an archive after (optionally) copying it from the local machine.
  action: unarchive
    src=           # Local archive path (copied) or remote path when remote_src=yes.
    dest=          # Destination directory on the remote host.
    remote_src=   # yes to use a remote archive directly.
    creates=       # Skip if the specified file already exists (idempotence).
    exclude=       # Patterns to exclude from extraction.
    keep_newer=    # Preserve newer files on the target.
    list_files=    # Return a list of files in the archive.
    mode= owner= group= # Set permissions/ownership for extracted files.

1.2.17 get_url module

Downloads files from HTTP/HTTPS/FTP or copies local files to remote hosts.

ansible-doc -s get_url
- name: Downloads files from HTTP, HTTPS, or FTP to node.
  action: get_url
    url=           # Source URL (http://, https://, ftp://, or file://).
    dest=          # Absolute destination path on the remote host.
    mode=          # Permissions for the downloaded file.
    force=         # yes to always download (default no).
    backup=        # Create a timestamped backup before overwriting.
    timeout=       # Connection timeout (seconds).
    tmp_dest=      # Temporary directory for download before moving.

1.2.18 wait_for module

Pauses play execution until a condition is met (port open, file exists, regex match, etc.).

ansible-doc -s wait_for
- name: Waits for a condition before continuing.
  action: wait_for
    host=          # Host to check (default 127.0.0.1).
    port=          # Port number to wait for.
    path=          # File path to wait for.
    search_regex= # Regex to match inside the file.
    state=         # present|started|stopped|absent|drained (default started).
    timeout=       # Maximum wait time (seconds, default 300).
    delay=         # Initial delay before checking.
    sleep=         # Sleep interval between checks.

1.2.19 script module

Transfers a local script to the remote host and executes it using the remote shell.

ansible-doc -s script
- name: Runs a local script on a remote node after transferring it.
  action: script
    free_form=    # Path to the local script plus any arguments.
    chdir=        # Change to this directory on the remote host before execution.
    creates=      # Skip execution if this file exists (idempotence).
    removes=      # Skip execution if this file does not exist.

For a complete list of modules and detailed documentation, visit the official Ansible module index at https://docs.ansible.com/ansible/latest/modules_by_category.html .

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 ManagementDevOpsModulesAnsible
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.