Skip to content
Velloreth
Technology 5 min read

Ansible Basics: Playbooks, Inventory and Idempotence

Ansible configures servers over SSH with no agent. Learn the inventory, the playbook, the modules and why idempotence matters.

By

What Ansible does

Ansible connects to a host over SSH, copies a small module, runs it, and removes it. There is no agent to install, which is the main difference from Puppet and Chef.

The model is declarative. A task describes the desired state, such as “the package nginx is present”, and the module decides whether anything needs to change.

The key property is idempotence. Running the same playbook twice produces the same result, and the second run reports no change.

The inventory

The inventory lists the hosts and groups them.

[web]
web1.example.com
web2.example.com

[db]
db1.example.com

[all:vars]
ansible_user=deploy
ansible_ssh_private_key_file=~/.ssh/deploy

A group is a set of hosts, and a group can contain another group.

[all:vars] sets variables for every host.

A dynamic inventory is a script or a plugin that returns the hosts, which is used when the hosts change.

ansible-inventory --list -i inventory.py

The playbook

A playbook is a YAML file with a list of plays.

---
- name: Configure the web servers
  hosts: web
  become: true
  vars:
    app_port: 8080
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Write the site configuration
      ansible.builtin.template:
        src: site.conf.j2
        dest: /etc/nginx/sites-available/site.conf
        mode: "0644"
      notify: Reload nginx

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

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

hosts selects the group. become runs with sudo. vars defines variables for the play.

A task has a name and a module. The name is what appears in the output, and it is worth writing clearly.

notify triggers a handler, and the handler runs once at the end.

Modules

A module is the unit of work. The common ones:

ModulePurpose
apt / dnfinstall a package
copycopy a file
templaterender a Jinja2 template
filemanage a file, directory or symlink
servicemanage a service
usermanage a user
gitclone a repository
command / shellrun a command
lineinfileensure a line in a file
urimake an HTTP request

command and shell are not idempotent by default, because Ansible cannot know whether the command changed anything. Use a module when one exists, and add a creates or changed_when guard when a command is unavoidable.

- name: Create the database
  ansible.builtin.command:
    cmd: createdb myapp
    creates: /var/lib/postgresql/myapp

creates makes the task skip if the path exists, which restores idempotence.

Variables and templates

A variable is defined in the playbook, in a group vars file, in a host vars file, or on the command line.

# group_vars/web.yml
app_port: 8080
app_name: myapp

A template is a Jinja2 file that is rendered with the variables.

server {
    listen {{ app_port }};
    server_name {{ ansible_hostname }};
    root /var/www/{{ app_name }};
}

The facts are variables Ansible discovers about the host, such as ansible_hostname, ansible_os_family and ansible_memtotal_mb.

- name: Install the right package
  ansible.builtin.package:
    name: nginx
    state: present
  when: ansible_os_family == "Debian"

Roles

A role is a reusable package with a fixed directory structure.

roles/nginx/
  tasks/main.yml
  handlers/main.yml
  templates/site.conf.j2
  defaults/main.yml
  vars/main.yml
  files/
  meta/main.yml

defaults has the lowest precedence and is meant to be overridden. vars has a higher precedence and is meant to be fixed.

A role is used in a play.

- hosts: web
  roles:
    - nginx
    - role: app
      vars:
        app_port: 9090

ansible-galaxy installs a role from a registry.

ansible-galaxy install geerlingguy.nginx

Running a playbook

# Check the syntax
ansible-playbook --syntax-check site.yml

# A dry run
ansible-playbook -i inventory site.yml --check

# Run it
ansible-playbook -i inventory site.yml

# Limit to one host
ansible-playbook -i inventory site.yml --limit web1.example.com

# Show the diff of a changed file
ansible-playbook -i inventory site.yml --diff

--check is the dry run. It reports what would change, and a module that does not support check mode reports a skip.

--diff shows the change to a file, which is the most useful flag when a template is wrong.

--limit restricts the run, which is how a change is tested on one host first.

Common mistakes

Using shell where a module exists. The task is not idempotent, and it reports changed every run.

A handler that is not notified. A configuration file changes and the service is not reloaded, so the change has no effect.

A secret in a playbook. Use ansible-vault or an external secret store.

ansible-vault encrypt group_vars/prod.yml
ansible-playbook -i inventory site.yml --ask-vault-pass

A task that assumes a fact. A playbook that works on Debian and fails on RHEL needs a when on the OS family.

A become on the whole play when only one task needs it. It is clearer to set it on the task.

A playbook that is not in version control. The configuration is code, and it belongs in a repository.

A run against production without --check first. A dry run on one host is cheap insurance.

A quotable summary

Ansible configures servers over SSH with no agent, using a declarative model where a task describes the desired state and a module makes it so. A playbook is a list of plays, a play is a list of tasks, and a task uses a module that is idempotent by design. A handler runs once at the end when it is notified, which is how a service is restarted after a change. Use a module rather than a shell command, keep secrets in a vault, and run with --check before a change reaches production.

For the infrastructure, see infrastructure-as-code-guide and terraform-basics. For the broader context, ci-cd-pipeline-basics and ssh-and-keys-guide.

Frequently asked questions

What is Ansible used for?
Ansible configures and deploys to servers over SSH. It installs packages, writes configuration files, manages services and runs commands, and it describes the desired state rather than the steps. It is used for server provisioning, application deployment and configuration management, and it needs no agent on the target.
What does idempotent mean in Ansible?
It means a task produces the same result whether it runs once or many times. A task that ensures a package is present installs it if it is missing and does nothing if it is already there. This is why a playbook can be run repeatedly, and why a task reports changed only when it actually changed something.
What is the difference between a playbook and a role?
A playbook is a file that lists plays and tasks. A role is a reusable package of tasks, handlers, variables and templates with a defined directory structure. A role is how a playbook is organised when it grows, and it can be shared and reused across projects.
What is a handler?
A handler is a task that runs only when it is notified by another task, and it runs once at the end of the play even if it was notified several times. It is the standard way to restart a service after a configuration file changes, so the service restarts once rather than after every task.
How does Ansible connect to a host?
By default over SSH, using the same key and user you would use manually. It needs Python on the target for most modules. There is no agent to install, which is the main difference from a tool such as Puppet or Chef.
What is a dynamic inventory?
It is an inventory generated by a script or a plugin rather than a static file. It queries a source such as a cloud provider or a container platform and returns the current hosts. It is used when the hosts change, so a static list would be out of date.