The Practitioner’s Guide to Scaling Infrastructure as Code

➡️ Download Now

Ansible

Ansible Cheat Sheet: CLI Commands and Basics

ansible cheat sheet

Ansible is a powerful automation tool for managing tasks like configuration management, application deployment, and system orchestration across a wide range of environments. It works without the need for agents and connects using SSH, making it easy to set up and operate. With Ansible, you can automate repetitive tasks across multiple systems using playbooks written in YAML. 

This cheat sheet provides a quick reference to essential Ansible commands and concepts. It helps you streamline your workflows, ensure consistency across environments, and maintain efficient operations. Whether you’re managing servers or deploying applications, this guide will help you get the most out of Ansible’s features.

  1. Ansible architecture and how it works
  2. Ansible installation and configuration commands
  3. Ansible inventory commands
  4. Ansible playbook structure and commands
  5. Ansible commands for roles
  6. Ansible Vault commands

Ansible architecture and how it works

ansible architecture

Ansible utilizes a push-based model via SSH to establish its tasks. It has two key pieces: control and managed nodes (hosts). The control node is the main server from which you execute your Ansible commands/playbooks, and the hosts are the servers in your Inventory file against which you would run your playbook tasks. 

Key Ansible components

Here’s an overview of Ansible’s main components:

  1. Playbooks: YAML files that contain all the tasks you want to run against your hosts.
  2. Modules: Can perform tasks such as copying a file or installing an application.
  3. Inventory: Collection of all the hosts you want to run your Playbooks against. This can be static or dynamic and be passed into your Ansible commands using the -i flag.
  4. Variables: You can store specific values to be used throughout your playbooks. These can also be passed in via Ansible Commands or defined in your playbooks or inventory. 
  5. Ansible facts: A way to retrieve information from the system you are running your playbook against
  6. Handlers: Specific tasks in a playbook that can trigger a handler, called during the end of a playbook
  7. Roles: Allow you to take repetitive tasks and store them in a single role, enabling reusability and structure for managing your Ansible environment.
  8. Ansible Vault: A secure store that allows Ansible to store sensitive passwords and files and can pass in the vault password or file through the command line 

Check out our beginner-friendly Ansible tutorial to get started.

Ansible installation and configuration commands

You can run the following commands to install Ansible to create a Control Node:

#Ubuntu
sudo apt update
sudo apt install software-properties-common
sudo apt-add-repository —-yes —-update ppa:ansible/ansible
sudo apt install ansible -y
#CentOS
sudo yum install epel-release -y
sudo yum install ansible -y

Host requirements

  • Python – Pre-Installed in most Linux distributions
  • SSH connectivity – Must establish SSH connectivity from the control node to the host

To create and deploy SSH key-pair to your hosts to ensure SSH connectivity:

sudo apt-get install openssh-server
ssh-keygen

Before running the following, you must ensure the user account you are logged in as on the control node exists in the hosts and has sudo rights:

ssh-copy-id hostname
ssh hostname

Once you confirm you can SSH into the hosts from the control node, you can start running Ansible commands and playbooks.

For more detailed information, see our guide: How to Install Ansible on Ubuntu, RHEL, macOS & CentOS

Ad-hoc commands

Ansible includes many commands you can execute from the control node, which can assist you in retrieving specific information about your hosts. 

The basic syntax for ad-hoc commands:

ansible <host-pattern> -m <module-name> -a “<module-arguments>

ansible -i ~/myinventory all -m ping – Ping and check for connection with ping module

ansible -i ~/myinventory all -m setup – Gather facts about your hosts with setup module

ansible -i ~/myinventory all -m shell -a "uptime" – Run a command on all hosts using shell module 

ansible -i ~/myinventory all -m shell -a "df -h" – Check disk space on all hosts using shell module

ansible -i ~/myinventory all -m command -a "cat /etc/passwd" – Check for all users on all hosts using the command module

ansible -i ~/myinventory all -m command -a "free -m" – Retrieve Memory information using the command module

Performing file operations on Hosts with Ansible using copy, fetch and file modules

ansible -i ~/myinventory all -m copy -a "src=/path/to/source dest=/path/to/destination" – Copy a file from Control Node to Host

ansible -i ~/myinventory all -m copy -a "src=/path/to/source dest=/path/to/destination" --check – Run a Copy file check to validate action before running

ansible -i ~/myinventory all -m fetch -a "src=/remote/path dest=/local/path" – Fetch a file from Host to the Control Node

ansible -i ~/myinventory all -m file -a "path=/path/to/directory state=directory mode=0755" – Create a directory on Hosts

ansible -i ~/myinventory all -m file -a "path=/path/to/file state=absent" – Remove a file or directory from Hosts

ansible -i ~/myinventory all -m file -a "src=/path/to/source dest=/path/to/symlink state=link" – Create a Symbolic Link on Hosts

Managing users and groups using the user module

ansible -i ~/myinventory all -m user -a "name=’username’ password=’<hashed_password>’ state=present" —-become —-ask-become-pass – Create a User. The password value must be hashed in order to run this command. You can use openssl or another tool to hash your password.

ansible -i ~/myinventory all -m user -a "name=username state=absent" – Add a User to Group

ansible -i ~/myinventory all -m user -a "name=username groups=admin append=yes" – Add a User to Group

Installing applications to Hosts

ansible -i ~/myinventory all -m apt -a "name=nginx state=present" – Install a Package using apt package manager

ansible -i ~/myinventory all -m yum -a "name=nginx state=present" – Install a Package using yum package manager

ansible -i ~/myinventory all -m apt -a "name=httpd state=absent" – Remove a Package using apt package manager

ansible -i ~/myinventory all -m yum -a "name=httpd state=absent" – Remove a Package using yum package manager

ansible -i ~/myinventory all -m apt -a "upgrade=dist" – Upgrade all Packages using apt package manager

ansible -i ~/myinventory all -m yum -a "upgrade=dist" – Upgrade all Packages using yum package manager

Managing services on hosts using service and systemd modules

ansible -i ~/myinventory all -m service -a "name=nginx state=started" – Start a service

ansible -i ~/myinventory all -m service -a "name=nginx state=stopped" – Stop a service

ansible -i ~/myinventory all -m systemd -a "name=nginx state=restarted" – Restart a service with systemd

ansible -i ~/myinventory all -m systemd -a "name=nginx enabled=yes" – Enable a service with systemd

Rebooting and shutting down Hosts

ansible -i ~/myinventory all -m reboot – Reboot all hosts

ansible -i ~/myinventory all -m command -a "/sbin/shutdown -h now" – Shutdown all hosts using command module

Mounting disks operations

ansible -i ~/myinventory all -m mount -a "path=/mnt/mydisk src=/dev/sdb1 fstype=ext4 state=mounted" – Mount a filesystem

ansible -i ~/myinventory all -m mount -a "path=/mnt/mydisk state=unmounted" – Unmount a filesystem

Using Cron module to manage Cron jobs

ansible -i ~/myinventory all -m cron -a "name='Backup' minute=0 hour=2 job='/usr/local/bin/backup.sh'" – Create a cron job

ansible -i ~/myinventory all -m cron -a "name='Backup' state=absent" – Remove a cron job

Ansible inventory commands

The Ansible inventory file lists hosts and groups of hosts in the following format:

[web] 
webserver1 ansible_host=192.168.11.7 ansible_user=root 
webserver2 ansible_host=192.168.11.8 ansible_user=root 

[db] 
dbserver1 ansible_host=192.168.12.10 ansible_user=dbadmin

Ansible inventory files can become complex, and the ansible-inventory commands allow you to quickly retrieve a clean list of all the hosts that are currently in your inventory.

ansible-inventory -i ~/myinventory --list – Display your inventory file in a JSON format

ansible-inventory -i ~/myinventory --list -y – Display your inventory file in a YAML format

ansible-inventory -i ~/myinventory --graph – Get a Tree structure of your inventory file

ansible-inventory -i ~/myinventory --host hostname – Find out specific information about a host in an inventory file

Ansible playbooks structure and commands

Ansible primarily uses playbooks that are written in YAML. The following is the basic YAML structure you will follow when you are writing your playbooks and organizing your plays. 

---
- hosts: all
  become: yes
  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present

    - name: Ensure Nginx is running
      service:
        name: nginx
        state: started

ansible-playbook is the main Ansible command to run playbooks against your hosts from the control node. 

We will cover a few basic commands you will always use and review a list of flags you can also utilize along with the ansible-playbook command.

Basic Ansible playbook commands

ansible-playbook myplaybook.yml -i ~/myinventory – Execute a playbook

ansible-playbook myplaybook.yml -i ~/myinventory --check – Dry-run a playbook before fully executing

ansible-playbook myplaybook.yml -i ~/myinventory --limit web – Specify inventory group on the command line level if the playbook is targeting all

ansible-playbook playbook.yml -v – Run playbook with verbose for troubleshooting purposes

ansible-playbook playbook.yml -vv – Extra verbose

ansible-playbook playbook.yml -vvv – Even more verbose

Useful flags to use with Ansible playbooks

ansible-playbook playbook.yml -i ~/myinventory --extra-vars "key1=value1 key2=value2" – Pass in extra variables from the command line to your playbook

ansible-playbook playbook.yml -i ~/myinventory --start-at-task "Install nginx package" – Start from a specific task 

ansible-playbook playbook.yml -i ~/myinventory -u <username> – Use specific user to connect to remote hosts

ansible-playbook playbook.yml -i ~/myinventory --ask-pass – Get prompted to enter password to SSH into Hosts instead of using SSH key pair

ansible-playbook playbook.yml -i ~/myinventory --ask-become-pass – Get prompted to escalate to sudo rights

ansible-playbook playbook.yml -i ~/myinventory --list-hosts – List all hosts in inventory that will be affected by this playbook

ansible-playbook playbook.yml -i ~/myinventory --step – Run your playbook step by step

ansible-playbook playbook.yml -i ~/myinventory --syntax-check – Check for syntax errors on the playbook before running

Ansible commands for roles

Roles allow you to organize your playbooks into reusable components. You can use them in either of two ways: create your own custom roles or install roles from the Ansible Galaxy, which is maintained by the community. 

To create your own custom roles, you will need to follow a specific directory structure. In this structure, you spread out your tasks, variables, files, handlers, and other components in separate directories with their own designated main.yml file. 

Creating custom role

You can run the following ansible-galaxy command to auto-create your own role directory structure:

# Initialize a new role directory structure 
ansible-galaxy init myrole

Giving you a directory structure as below: 

my_role/
├── defaults/
│   └── main.yml        # Default variables for the role
├── files/              # Files that can be copied to remote hosts
├── handlers/
│   └── main.yml        # Handlers (e.g., to restart a service)
├── meta/
│   └── main.yml        # Role metadata (dependencies, etc.)
├── tasks/
│   └── main.yml        # Main list of tasks
├── templates/          # Jinja2 templates that can be deployed to hosts
├── tests/
│   └── inventory       # Test inventory
│   └── test.yml        # Test playbook
├── vars/
│   └── main.yml        # Variables specific to the role

The key directory is /tasks/main.yml. Here you add your playbook tasks as below: 

---
- name: Install Nginx
  yum:
    name: nginx
    state: present

- name: Start Nginx service
  service:
    name: nginx
    state: started

Ansible Galaxy roles

To install a role from the Ansible Galaxy community, follow this syntax:

ansible-galaxy install <username>.<rolename>

Here is an example of installing the Apache role that is maintained by geerlingguy:

ansible-galaxy install geerlingguy.apache

Referencing a role in a playbook

To use this role in a playbook, you need to reference the role under the roles keyword in the playbook:

---
- hosts: webservers
  roles:
    - my_role

Ansible Galaxy commands

You can also utilize ansible-galaxy commands to manage your Ansible roles. Below are a few commands that can be used when managing your roles:

ansible-galaxy list --role-path ~/roles – List all Ansible roles in your local roles directory

ansible-galaxy collection list – List all Ansible roles in the Community managed roles directory

ansible-galaxy role list – List all Ansible roles installed on your Control Node

ansible-galaxy info /path/to/local/role – View information of your custom role

ansible-galaxy info grafana  – View information of a galaxy role

ansible-galaxy search <role_name> or ansible-galaxy search apache– Search for a role by a specific topic or key in Ansible Galaxy

ansible-galaxy remove grafana – Remove a role from your system

Ansible Vault commands

Ansible Vault allows you to encrypt sensitive data such as passwords, private keys, and other confidential information that are used within playbooks and variables. 

By encrypting these values, Ansible ensures your sensitive information is protected, even if the playbooks are stored in a public repository. With Vault, you can encrypt files and decrypt them during playbook execution with the vault password. 

ansible-vault create secrets.yml – Create an encrypted file to store secrets.

You will be prompted to enter a password and have to add your password in key:value format, as the following:

db_user: my_user
db_password: my_password

You can reference the keys as variables in your playbook as the following:

---
- hosts: dbservers
  vars_files:
    - secrets.yml
  tasks:
    - name: Show DB user and password
      debug:
        msg: "The DB user is {{ db_user }} and password is {{ db_password }}"

To run the playbook, you will need to either enter the vault password by using the ask-vault-pass flag or pass in the password through a vault-password-file:

ansible-playbook playbook.yml --ask-vault-pass – Enter password

ansible-playbook playbook.yml --vault-password-file /path/to/vault_password – Pass in the Vault password file

Managing Ansible vault files

ansible-vault encrypt vars.yml – Encrypt existing file

ansible-vault decrypt vars.yml – Decrypt encrypted file

ansible-vault view secrets.yml – View encrypted file

ansible-vault edit secrets.yml – Edit encrypted file

ansible-vault rekey secrets.yml – Change password for encrypted file

Why use Spacelift to elevate your Ansible automation?

Spacelift’s vibrant ecosystem and excellent GitOps flow can greatly assist you in managing and orchestrating Ansible. By introducing Spacelift on top of Ansible, you can easily create custom workflows based on pull requests and apply any necessary compliance checks for your organization.

With Spacelift, you get:

  • Better playbook automation – Manage the execution of Ansible playbooks from one central location.
  • Inventory observability – View all Ansible-managed hosts and related playbooks, with clear visual indicators showing the success or failure of recent runs.
  • Playbook run insights – Audit Ansible playbook run results with detailed insights to pinpoint problems and simplify troubleshooting.
  • Policies – Control what kind of resources engineers can create, what parameters they can have, how many approvals you need for a run, what kind of task you execute, what happens when a pull request is open, and where to send your notifications
  • Stack dependencies – Build multi-infrastructure automation workflows with dependencies, having the ability to build a workflow that, for example, generates your EC2 instances using Terraform and combines it with Ansible to configure them
  • Self-service infrastructure via Blueprints, or Spacelift’s Kubernetes operator – Enable your developers to do what matters – developing application code while not sacrificing control
  • Creature comforts such as contexts (reusable containers for your environment variables, files, and hooks), and the ability to run arbitrary code
  • Drift detection and optional remediation

If you want to learn more about using Spacelift with Ansible, check our documentation, read our Ansible guide, or book a demo with one of our engineers.

Would you like to see this in action – or just want a tl;dr? Check out this video I put together showing you Spacelift’s new Ansible functionality:

ansible product video thumbnail

Key points

Ansible is a versatile, powerful tool that simplifies infrastructure management and automates your workflows at scale. With its agentless architecture, Ansible lets you connect to hosts effortlessly over SSH, using intuitive YAML-based playbooks to define tasks.

This Ansible cheat sheet offers a range of essential commands and techniques to help you unlock Ansible’s full potential. From executing ad-hoc tasks and creating custom roles to securing sensitive data with Ansible Vault, it provides quick ways to streamline repetitive tasks, enforce consistent configurations, and boost the operational efficiency of your infrastructure. Whether you’re a beginner or an experienced user, these tips will guide you toward more seamless automation.

Manage Ansible Better with Spacelift

Managing large-scale playbook execution is hard. Spacelift enables you to automate Ansible playbook execution with visibility and control over resources, and seamlessly link provisioning and configuration workflows.

Learn more

Elevate Your Ansible Automation

Strengthen control, enhance inventory visibility,

and unify your infrastructure pipeline.

Learn more
ansible bottom overlay