logo

Cheatsheet - Ansible

CheatSheet

This cheatsheet covers the essential components of Ansible, from one-liner ad-hoc commands to complex playbook structures.

1. Inventory Management

The inventory file (usually hosts or hosts.ini) defines the nodes you are managing.

INI Format (/etc/ansible/hosts):

[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com

[production:children]
webservers
dbservers

Common Inventory Commands:

  • ansible all --list-hosts — List all managed nodes.
  • ansible webservers -m ping — Test connection to a specific group.

2. Ad-Hoc Commands

Used for quick, one-time tasks without writing a playbook.

Syntax: ansible <group> -m <module> -a "<arguments>"

  • Ping: ansible all -m ping
  • Run Shell Command: ansible all -a "uptime"
  • Install Package: ansible web -m apt -a "name=nginx state=present" --become (--become for sudo)
  • Manage Services: ansible all -m service -a "name=sshd state=restarted"
  • Copy File: ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts"

3. Playbook Structure

Playbooks are YAML files that define a desired state.

Example: site.yml

---
- name: Setup Web Server
  hosts: webservers
  become: yes # Run as sudo
  vars:
    http_port: 80

  tasks:
    - name: Install Nginx
      ansible.builtin.apt:
        name: nginx
        state: present

    - name: Start Nginx service
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: yes

Running Playbooks:

  • ansible-playbook site.yml — Run the playbook.
  • ansible-playbook site.yml --checkDry run (see changes without applying).
  • ansible-playbook site.yml --limit web1 — Run only on a specific host.
  • ansible-playbook site.yml --syntax-check — Check for YAML errors.

4. Common Modules

Module Purpose Example Argument
apt / yum Package management name=git state=latest
copy Copy local file to remote src=foo.conf dest=/etc/foo.conf
template Copy Jinja2 template src=vhost.j2 dest=/etc/nginx/conf.d/
file Set permissions/symlinks path=/etc/foo.conf mode=0644
lineinfile Ensure a line exists in a file path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing'
git Deploy software from git repo=https://github.com/foo.git dest=/src
debug Print statements/vars msg="Variable is {{ my_var }}"

5. Variables & Facts

Defining Variables:

  • In Playbook: vars: pkg_name: nginx
  • In Files: vars_files: - vars.yml
  • In Inventory: web1 ansible_user=ubuntu

Using Variables:

  • {{ variable_name }} (Always quote if it starts a line: "{{ var }}")

Ansible Facts: Ansible automatically gathers system info (IP, OS, CPU).

  • ansible all -m setup — View all available facts for a host.
  • Usage: {{ ansible_facts['os_family'] }}

6. Logic: Conditionals & Loops

Loops:

- name: Install multiple packages
  apt:
    name: '{{ item }}'
    state: present
  loop:
    - git
    - curl
    - vim

Conditionals:

- name: Shut down Debian systems
  command: /sbin/shutdown -t now
  when: ansible_facts['os_family'] == "Debian"

7. Ansible Vault (Security)

Used to encrypt sensitive data like passwords or API keys.

  • Create Encrypted File: ansible-vault create secret.yml
  • Encrypt Existing File: ansible-vault encrypt vars.yml
  • Edit Encrypted File: ansible-vault edit vars.yml
  • Run Playbook with Vault: ansible-playbook site.yml --ask-vault-pass

8. Roles & Galaxy

Roles allow you to bundle variables, tasks, and templates into reusable directory structures.

Standard Directory Layout:

roles/
  common/
    tasks/main.yml
    handlers/main.yml
    templates/ntp.conf.j2
    vars/main.yml

Using Ansible Galaxy:

  • ansible-galaxy init my_new_role — Create role skeleton.
  • ansible-galaxy install geerlingguy.nginx — Download a community role.

9. Handlers

Handlers are tasks that only run when "notified" by another task (usually to restart a service after a config change).

tasks:
  - name: Update Nginx config
    template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
    notify: Restart Nginx

handlers:
  - name: Restart Nginx
    service: name=nginx state=restarted

10. Useful Flags

  • -v, -vv, -vvv — Increase verbosity (debugging).
  • --become / -K — Run as sudo and prompt for password.
  • -u <user> — Connect as a specific SSH user.
  • --start-at-task="task name" — Jump to a specific task in a playbook.

FAQ

What are Built-in Ansible tasks?

"Built-in" Ansible tasks refer to the collection of modules and plugins that are part of the ansible.builtin collection. These are the foundational building blocks included by default with ansible-core.

For example:

Copy files

  • ansible.builtin.copy: from local to remote.
  • ansible.builtin.fetch: from remote to local.
  • ansible.builtin.slurp: fetching a base64-encoded blob containing the data in a remote file.

Execute

  • ansible.builtin.command: execute command on selected nodes.
  • ansible.builtin.shell: almost exactly like the ansible.builtin.command module but runs the command through a shell (/bin/sh) on the remote node.
  • ansible.builtin.script: The local script at path will be transferred to the remote node and then executed. does not require python on the remote system

What makes Ansible special?

The key difference / advantage is agent-less.

  • Target machines / nodes are termed as "inventory"
  • only depend on OpenSSH and Python
  • Playbooks use an easy and descriptive language based on YAML and Jinja templates.

It also has a strong focus on security and reliability, featuring a minimum of moving parts, usage of OpenSSH for transport (with other transports and pull modes as alternatives), and a language that is designed around auditability by humans–even those not familiar with the program.

Ansible is an IT automation tool. It can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero downtime rolling updates.

Ansible can be used to manage bare metal machines: configuring the machines, installing packages, and Kubernetes components.

What are the Key features?

  • Agentless: SSH protocol is used to connect to servers and work on them instead of external agents; (Chef and Puppet follow master-agent or master-slave architecture.)
  • Idempotent: same operations provide the same result as many times as they are carried out;
  • Easy and expandable: Ansible is written in Python and uses YAML to write the commands. (Chef and Puppet use Ruby DSL.)

Ansible vs Ansible Tower vs ansible-runner

  • Ansible: open source
  • Ansible Tower: enterprise version
  • ansible-runner: a wrapper around Ansible execution. Ways to use it:
    • A stand alone ansible-runner CLI command.
    • A reference container image for k8s.
    • A python module.

Is Ansible Declarative or Procedural?

Ansible can be both declarative and procedural: many modules work declaratively, while other modules prefer a procedural programming approach. Additionally, some constructs in the Ansible language, such as conditionals and loops, allow the users to define a procedural logic.

Ansible Competitors

The Configuration Management (CM) market is generally divided into the "Big Four" (Ansible, Puppet, Chef, and SaltStack) and the "Provisioners" (Terraform).

Ansible's massive popularity is due to its simplicity and agentless architecture. Here is how it stacks up against the rest.

1. Ansible vs. Puppet & Chef (The "Old Guard")

Puppet and Chef were the industry leaders before Ansible arrived.

Feature Ansible Puppet Chef
Architecture Agentless (Uses SSH/WinRM) Agent-based (Needs software on nodes) Agent-based (Needs software on nodes)
Language YAML (Simple) Puppet DSL (Ruby-like) Ruby (Full programming)
Setup Fast/Easy Complex (Master/Agent setup) Complex (Chef Server/Workstation)
Model Push: Master pushes changes Pull: Nodes check-in for updates Pull: Nodes check-in for updates
  • Why choose Ansible: You want to get started in an hour. You don't want to install and manage agent software on 500 servers.
  • Why choose Puppet/Chef: You have a massive, static fleet (10,000+ nodes) and want to ensure "State Enforcement." Agents are better at correcting "configuration drift" automatically every 30 minutes without a master triggering it.

2. Ansible vs. SaltStack (The Speed Demon)

SaltStack is Ansible's closest architectural competitor.

  • Architecture: Salt is typically agent-based (Minions) using a high-speed bus (ZeroMQ), but it can also run agentless.
  • Speed: Salt is much faster than Ansible. Because Ansible uses SSH, it has to open a new connection for every task. Salt keeps a persistent socket open.
  • Language: Both use YAML, but Salt allows for much more complex Python logic.
  • Verdict: Choose Salt if you are managing extreme scale or need event-driven orchestration (e.g., "If Server A's CPU hits 90%, Salt automatically triggers Server B to scale").

3. Ansible vs. Terraform (The Provisioner)

This is the most common comparison, but they are actually partners, not competitors.

  • Terraform is for Infrastructure (The "House"): It creates the VMs, the VPCs, the Subnets, and the Cloud Databases. It is "Declarative"—it focuses on the end state.
  • Ansible is for Configuration (The "Furniture"): Once the VM exists, Ansible goes inside to install Nginx, update the OS, and deploy the application code.
  • The "Golden Image" Shift: Many modern teams use Terraform to build infrastructure and Packer to build images, making Ansible less necessary for day-to-day config but still vital for day-to-day operations.

4. Summary Table: At a Glance

Tool Learning Curve Speed Best For...
Ansible 🟢 Easy 🟡 Moderate General automation, app deployment, quick tasks.
Terraform 🟡 Moderate 🟢 Fast Cloud infrastructure provisioning (AWS/GCP/Azure).
SaltStack 🔴 Steep 🚀 Blazing High-scale environments and event-driven automation.
Puppet 🔴 Steep 🟢 Fast Enforcing strict compliance and state in large enterprises.
Chef 🔴 Steep 🟢 Fast Teams with strong Ruby/Developer backgrounds.

The Final Verdict: Why Ansible usually wins

Ansible has won the "mindshare" of the DevOps community for three reasons:

  1. Low Barrier to Entry: If you know how to write a list in YAML, you can use Ansible.
  2. No "Bootstrap" Problem: With Puppet/Chef, you need a way to install the agent before you can manage the server. With Ansible, if you have SSH access, you're done.
  3. Versatility: It isn't just for servers. Ansible is now the industry standard for Network Automation (configuring Cisco/Arista switches) because those devices cannot run agent software.