Hot Summer Sale - up to 36% OFF

Ansible Cheat Sheet: Ansible Command Guide

Ansible Cheat Sheet: Ansible Command Guide
Published on Jul 21, 2025 Updated on Jul 21, 2025

Ansible automates infrastructure management without requiring agents on remote systems. It connects to machines using SSH on Linux and WinRM on Windows and executes tasks defined in YAML-based playbooks.

This guide covers essential Ansible commands for managing servers and executing tasks. It explains how to efficiently define an inventory structure, run ad-hoc commands, and execute playbooks. Advanced sections focus on privilege escalation, debugging, and best practices to improve automation workflows. Each section provides practical commands and structured examples for enabling integration into existing infrastructure.

#What is Ansible?

Ansible is an open-source tool that enables you to perform infrastructure as code. It uses playbooks to define automation jobs and operates by connecting to nodes to execute small programs called Ansible modules. These modules bring systems to the desired state and are removed after execution. Ansible is agentless and relies on SSH for communication. It also requires no software installation on managed nodes.

Ansible is easy to set up, so it is the most suitable tool to automate vast IT environments.

Key benefits of Ansible include:

  • Agentless: No need to install software on remote machines.
  • Human-readable automation: Playbooks are YAML files, making them machine-parsable and easily understandable.
  • Idempotent execution: Re-running the same tasks results in a consistent system state.
  • Large ecosystem: A wide variety of modules, community roles, and playbooks.

Run your deployments in a scalable and cost-effective open cloud infrastructure. Cherry Servers' secure virtual private servers offer automatic scaling, flexible pricing, and 24/7 technical support. Our pre-defined Ansible module helps you automate the installation and configuration.

#Ansible basics

Before going into commands, let's first understand the foundational elements that make Ansible work.

  • Control node: The machine from which you run Ansible commands (often your local machine or an administrative server).

  • Managed hosts: The servers or devices that Ansible configures. These targets are grouped in an inventory file.

  • Inventory file: A file listing the target hosts and groups, usually named hosts or inventory. It can be in INI or YAML format.

    Example:

    [webservers]
    web1.example.com
    web2.example.com
    
    [dbservers]
    db1.example.com
    
  • Modules: Reusable units of code that perform tasks such as installing packages and creating users. Modules are called by the Ansible engine to do the actual work.

  • Tasks: A task is a directive that calls a module. In a playbook, tasks are listed in sequence under a play. Each task targets one or more hosts.

  • Playbooks: The YAML files that define which tasks should be run and on which hosts. Example:

    - name: Install Nginx on web servers
      hosts: webservers
      become: yes
      tasks:
        - name: Install Nginx
          apt:
            name: nginx
            state: present
    
  • Roles: A structured way to group tasks, variables, handlers, and other components in separate directories, making your Ansible code more organized and reusable.

  • Handlers: Special tasks triggered at the end of a play only if a specific “notify” directive is used. Often used for restarting services after configuration changes.

  • Variables: Configurations used to parameterize your tasks for different environments. Commonly stored in group_vars, host_vars, or within the playbook.

#Ansible commands cheat sheet

Below is a quick reference for commonly used Ansible commands and their essential options.

1. Check Ansible version

ansible --version

This displays the installed Ansible version along with the default configuration file paths.

2. Test connectivity (ping module)

ansible  -m ping all -i inventory
  • -m ping calls the ping module to verify connectivity to all hosts in the inventory file.

  • all means every host in the inventory. You can target hosts in a host group by specifying the host group name. For example, you can pass the webservers host group as follows.

Command Line
ansible  -m ping webservers -i inventory

-i option specifies the path to a custom inventory file. If not provided, Ansible falls back to the default inventory, which is /etc/ansible/hosts.

3. Ad-hoc commands Run one-off commands without writing a playbook, which is helpful for quick tasks and verification.

# Example: Checking disk usage on all managed hosts.

ansible  -m shell all -a "df -Th" -i inventory

The -m shell option uses the shell module to execute commands on remote targets, while the -a the flag passes the command arguments, in this case df -Th.

4. Running playbooks To run an Ansible playbook containing the automation tasks run the command below. This allows you to apply configurations across multiple hosts defined in your inventory.

ansible-playbook site.yml -i inventory
  • site.yml is a playbook containing tasks to execute.
  • -i inventory points to the path of your custom inventory file. If not specified, Ansible will fall back to the default inventory.

Common options:

  • --check runs the playbook in “dry run” mode (no changes are made).
  • --diff Shows changes that will be made to files.
  • --limit <host or group> Limits the play to specific hosts or groups.

Example:

ansible-playbook site.yml -i inventory --check --diff --limit web1.example.com

With --check, the command executes the Ansible playbook in dry run mode to display intended modifications. The command targets a single host called web1.example.com from the specified inventory using -i inventory.

5. Privilege escalation (become)

If you need to run commands with elevated privileges, add:

--become

In Ansible, when we talk about 'elevated privileges,' we're saying a task needs 'superuser' authorization to get things done. You might be acting as the root account or another administrator account. (or -b for short).

For ad-hoc commands:

ansible all -m ping -b -i inventory

The command runs the ping module on all hosts listed in the specified inventory file (-i inventory), using privilege escalation using -b for become/sudo to check the connectivity and ensure Ansible can communicate with the hosts.

For playbooks (YAML):

- name: Example play
  hosts: all
  become: yes
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes

To run an Ansible playbook with privilege escalation and prompt for the BECOME password, use the --ask-become-pass flag (or -K for short). This ensures that Ansible asks for the sudo password when executing tasks requiring elevated privileges.

ansible-playbook playbook.yaml -i inventory --ask-become-pass

or using the shorthand:

ansible-playbook playbook.yaml -i inventory -K

This will prompt you for the BECOME password before executing the playbook.

6. Using tags

Tags allow you to run specific parts of a playbook. Tags can be defined in tasks, then run or skipped via CLI options.

Run tasks by tag:

ansible-playbook site.yml --tags "install"

The command above runs the Ansible playbook (site.yml), but only executes tasks tagged with "install", skipping all other tasks.

Skip tasks by tag:

ansible-playbook site.yml --skip-tags "config"

The command runs the Ansible playbook (site.yml) but skips any tasks tagged with "config", executing all other tasks.

Example in a playbook:

---
- name: Install Nginx web server
  hosts: webservers

  tasks:
    - name: Install packages
      apt:
        name: nginx
        state: present
      tags:
      - install

    - name: Configure nginx
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      tags:
      - config

7. Gathering facts

By default, Ansible collects system information called "facts" at the start of each play. You can manually gather or skip them:

ansible all -m setup -i inventory

The setup module prints all available facts. Disabling facts speeds up your play if you don’t need them:

- hosts: all
  gather_facts: no
  ...

8. Managing roles

Roles help you organize your tasks, handlers, and variables. Create a new role structure:

ansible-galaxy init <role_name>

This command creates the necessary folders for your role.

9. Fetching information from hosts

ansible all -m command -a "uname -a" -i inventory

The command module is a simpler version of the shell without the shell environment overhead. Use it to gather information quickly from remote hosts.

10. Checking syntax Validating a playbook’s syntax before running it ensures you haven’t introduced errors:

ansible-playbook site.yml --syntax-check

#Ansible debugging, troubleshooting, and best practices

Ansible requires debugging and logging to ensure smooth automation workflows. This section explores debugging techniques, logging, and best practices to improve your Ansible workflow.

#Debugging and troubleshooting in Ansible

Ansible provides multiple ways to enable debugging and verbosity for better troubleshooting:

1. Verbose logging

Use the -v, -vv, -vvv, or -vvvv flags to control the level of verbosity in ansible-playbook:

ansible-playbook site.yml -vvv
  • -v - Basic output (tasks being executed)
  • -vv - Detailed information on tasks
  • -vvv - Includes connection details and module execution logs
  • -vvvv - Full debug mode (includes variable values, SSH details)

2. Enable Ansible debug mode

Set the ANSIBLE_DEBUG environment variable for more detailed output:

export ANSIBLE_DEBUG=1
ansible-playbook site.yml

3. Logging output to a file

If you need persistent logs set the ANSIBLE_LOG_PATH variable:

export ANSIBLE_LOG_PATH=/var/log/ansible.log
ansible-playbook site.yml

This is similar to enabling Terraform debugging logs and provider logs.

#Viewing module and task execution logs

When debugging failures, Ansible provides multiple tools to inspect tasks:

1. Check Ansible facts

Run the following command to gather system facts:

ansible all -m setup

2. Use debugging with debug module

If a task isn’t behaving as expected, insert a debug statement to inspect variable values:

- name: Debugging variables
  debug:
    var: ansible_facts['os_family']

3. Dry run mode (--check)

You can use --check mode to preview changes without making modifications:

ansible-playbook site.yml --check

#Best practices & useful tips for Ansible

Following best practices in Ansible helps create efficient and secure automation workflows. Keeping playbooks clean, managing secrets properly, and optimizing task execution improve reliability. This section covers ignoring unnecessary linting warnings, securing sensitive data with ansible-vault, and following essential guidelines for better automation.

1. Using .ansible-lint-ignore

Ansible has a similar feature with ansible-lint to ignore specific linting rules, create .ansible-lint-ignore:

roles/myrole/tasks/main.yml  # Ignore linting for this file

Or, you can ignore specific rules inline:

- name: Example Task
  command: echo "Hello"
  # noqa command-instead-of-module

This ensures unnecessary warnings don't clutter your workflow.

2. Keeping secrets secure with ansible-vault

Terraform stores sensitive data in its state file, requiring encryption and secure storage. Similar to Terraform, Ansible secrets should be encrypted using ansible-vault.

3. Encrypt a file

ansible-vault encrypt secrets.yml

4. Decrypt for editing

ansible-vault edit secrets.yml

5. Use Vault in Playbooks

vars_files:
  - secrets.yml

This ensures sensitive credentials are not exposed in plain text.

#Using ansible-playbook --diff

Ansible has a --diff flag that helps detect what will change before applying it:

ansible-playbook site.yml --check --diff

This is useful when working with configuration files where changes should be reviewed before execution.

#Conclusion

This guide covered essential Ansible concepts, including playbook inventory management and ad-hoc commands privilege escalation. Key best practices, such as using ansible-vault for secrets and --diff for change tracking, help ensure secure and efficient automation.

We also covered challenges like debugging unexpected failures and optimizing playbook performance that may arise while using Ansible.

Cloud VPS Hosting

Starting at just $3.24 / month, get virtual servers with top-tier performance.

Share this article

Related Articles

Published on Jan 16, 2025 Updated on Jan 17, 2025

How to Use Ansible Vault in Playbook? Secure Your Configuration

Learn to secure sensitive data in Ansible Playbooks using Ansible Vault. Encrypt files, variables, and manage secrets with step-by-step guidance and best practices.

Read More
Published on Sep 16, 2024 Updated on Feb 4, 2025

How Does When Condition Work in Ansible

Learn how the when condition works in Ansible to control task execution based on variables, facts, and conditions. Optimize your playbooks with this detailed guide.

Read More
Published on Feb 17, 2022 Updated on Feb 27, 2025

How to Create and Use Ansible Playbooks

Ansible playbook is a robust way to repeatedly perform multiple tasks on a number of servers. Learn how to create and use Ansible playbooks yourself.

Read More
We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: a49892c77.1299