This Ansible playbook tutorial takes you from an empty folder to a working automation project: an inventory of Linux servers, a playbook that installs and configures nginx, a handler that reloads the service only when its configuration changes, and finally a reusable role checked with ansible-lint. Every file shown here was syntax-checked and linted with ansible-core 2.22, the current release.
Quick answer: an Ansible playbook is a YAML file that lists one or more plays. Each play targets a group of hosts from your inventory and runs tasks in order, and each task calls a module such as ansible.builtin.apt or ansible.builtin.template. You run it with ansible-playbook -i inventory.ini site.yml, and a second run should report no changes.
If you prefer to learn with a trainer and guided labs, our live Ansible training course covers the same ground and goes much further, into Vault, Molecule testing and execution environments.
Key takeaways
- Ansible is agentless: the control node connects over SSH, and managed nodes only need Python and a user that can log in.
- A playbook describes the state you want. Well-written tasks are idempotent, so running them again changes nothing.
- Use fully qualified collection names such as
ansible.builtin.service, keep variables ingroup_vars, and use handlers for restarts. - Preview every change with
--check --diffbefore you apply it, and runansible-lintto catch problems early. - Once a playbook works, move its tasks into a role so you can reuse and test them.
What you need before you start
Ansible runs from a control node and manages managed nodes. The control node can be almost any Linux or macOS machine with Python. Windows is not supported as a native control node, so on a Windows laptop use WSL. Managed nodes do not need Ansible installed at all; they need Python and an account you can reach over SSH.
For this tutorial you need:
- A control node (your laptop, a Linux VM or WSL).
- One or two Ubuntu servers you can SSH into with a key, for example small VMs or cloud free tier instances. The examples use the user
ubuntuand the documentation addresses 192.0.2.10 and 192.0.2.11; replace them with your own. - A user on those servers that can run
sudo, because installing packages needs root privileges.
Install Ansible on the control node
There are two packages. ansible-core is the minimal engine with the built-in modules (the ansible.builtin collection). ansible is the larger community package that adds a curated set of collections on top of ansible-core. For this tutorial either works. The official install guide recommends pipx on systems where the operating system restricts pip:
pipx install --include-deps ansible
# or the minimal engine only
pipx install ansible-core
# check what you installed
ansible --version If you do not use pipx, python3 -m pip install --user ansible also works. The newest ansible-core release, 2.22, needs Python 3.13 or later on the control node. If your system Python is older, pip and pipx install the newest ansible-core release that still supports it, which is fine for everything in this guide.
Step 1: Create a project folder and an inventory
An inventory tells Ansible which machines exist and how to group them. Create a folder for the project and add an INI inventory with one group called web:
mkdir ansible-web && cd ansible-web # inventory.ini
[web]
web1 ansible_host=192.0.2.10
web2 ansible_host=192.0.2.11
[web:vars]
ansible_user=ubuntu Each line gives a host a short name (web1) and the address Ansible should connect to (ansible_host). The [web:vars] block sets the SSH user for every host in the group. INI is the quickest format for a handful of hosts; the same data can be written as YAML when the inventory grows.
To avoid typing -i inventory.ini on every command, add a small ansible.cfg in the same folder:
# ansible.cfg
[defaults]
inventory = inventory.ini Now check that Ansible reads the inventory and can reach every host:
ansible-inventory --list
ansible web -m ansible.builtin.ping The ping module is not a network ping. It logs in over SSH, checks that a usable Python exists and replies with "ping": "pong". If a host shows UNREACHABLE, fix SSH first: confirm you can run ssh [email protected] by hand with your key.
Step 2: Write your first Ansible playbook
The playbook below installs nginx, writes a site configuration and a home page from templates, and makes sure the service is running and enabled at boot. Save it as webserver.yml:
---
- name: Configure web servers
hosts: web
become: true
vars:
http_port: 80
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600
- name: Deploy the site configuration
ansible.builtin.template:
src: templates/site.conf.j2
dest: /etc/nginx/sites-available/default
owner: root
group: root
mode: "0644"
notify: Reload nginx
- name: Publish the home page
ansible.builtin.template:
src: templates/index.html.j2
dest: /var/www/html/index.html
owner: root
group: root
mode: "0644"
- name: Make sure nginx is running and starts on boot
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded How to read this playbook
- hosts: web targets the group from the inventory.
- become: true runs tasks with sudo. If your user needs a sudo password, add
-K(--ask-become-pass) when you run the playbook. - Each task calls one module by its fully qualified collection name.
ansible.builtin.aptmanages Debian and Ubuntu packages; on Red Hat family systems you would useansible.builtin.dnf, oransible.builtin.packagefor a distribution-neutral task. - update_cache with cache_valid_time: 3600 refreshes the apt package index only if it is more than an hour old, which keeps repeat runs fast.
- notify queues the
Reload nginxhandler, but only when that task actually changes the file.
Step 3: Add variables and Jinja2 templates
Templates let one playbook produce different files for different hosts or environments. Create a templates folder with two files. The first is the nginx site configuration, which reads the http_port variable from the play:
# templates/site.conf.j2
server {
listen {{ http_port }} default_server;
root /var/www/html;
index index.html;
} The second is a simple home page:
<!-- templates/index.html.j2 -->
<!doctype html>
<html>
<head><title>{{ site_title }}</title></head>
<body>
<h1>{{ site_title }}</h1>
<p>Served by {{ inventory_hostname }}, managed by {{ site_owner }}.</p>
</body>
</html> inventory_hostname is a built-in variable holding the host’s inventory name, so each server’s page shows web1 or web2. The other two variables belong to the whole group, so put them in a group_vars file named after the group. Ansible loads it automatically because it sits next to the inventory:
# group_vars/web.yml
site_title: "Hello from Ansible"
site_owner: "Platform team" Run ansible-inventory --list again and you will see site_title and site_owner attached to both hosts. Ansible has a long variable precedence order; for now remember that role defaults are the easiest values to override, group variables override them, host variables override group variables, and extra variables passed with -e always win.
Step 4: Check, preview and run the playbook
Build the habit of testing before you touch servers. These commands work without changing anything:
# catch YAML and structure errors
ansible-playbook webserver.yml --syntax-check
# list the tasks that would run
ansible-playbook webserver.yml --list-tasks
# predict changes and show file differences
ansible-playbook webserver.yml --check --diff Check mode asks each module to report what it would change without changing it, and --diff shows line-by-line differences for files and templates. On a brand-new server the check run may stop at a later task because nginx is not installed yet, which is expected: check mode can only predict, it does not install anything.
When you are happy, apply it:
ansible-playbook webserver.yml Ansible prints each play and task, then a PLAY RECAP line per host with counters such as ok, changed, unreachable, failed and skipped. Open http://192.0.2.10/ in a browser and you should see your page.
Step 5: Prove the playbook is idempotent
Run exactly the same command a second time. Most Ansible modules first check whether the system is already in the requested state and do nothing if it is, so this time the recap should show changed=0 for every host, and the handler does not run. That property, called idempotency, is what makes playbooks safe to run on a schedule or from a CI pipeline.
Now change something real. Edit group_vars/web.yml and set site_title to a new value, then run the playbook again. Only the Publish the home page task reports a change. Change http_port and the configuration task changes too, which triggers Reload nginx once at the end of the play, no matter how many tasks notified it.
A common beginner mistake breaks idempotency: using ansible.builtin.command or ansible.builtin.shell for work a module already does, such as running apt-get install yourself. Those modules report a change on every run because Ansible cannot know what the command did. Prefer a purpose-built module, and reach for command only when none exists.
Step 6: Turn the playbook into a reusable role
A playbook is fine for one job. When you want the same setup in several projects, package it as a role. Generate the standard structure:
ansible-galaxy role init roles/webserver This creates folders such as tasks, handlers, templates, defaults, vars and meta, each with a main.yml where one is expected. Move the pieces across:
- The task list goes into
roles/webserver/tasks/main.yml(just the list, without the play header). - The handler goes into
roles/webserver/handlers/main.yml. - Both
.j2files go intoroles/webserver/templates/. Inside a role,src: site.conf.j2is enough because Ansible looks in the role’s templates folder. - The port becomes a role default in
roles/webserver/defaults/main.yml, so any inventory can override it.
# roles/webserver/defaults/main.yml
---
webserver_http_port: 80 Notice the new name. ansible-lint recommends prefixing role variables with the role name, which prevents clashes when you combine many roles; update the template to use {{ webserver_http_port }}. The playbook itself shrinks to a few lines:
# site.yml
---
- name: Configure web servers
hosts: web
become: true
roles:
- webserver Lint before you commit
ansible-lint checks playbooks, roles and collections against community best practices. Install it with pipx install ansible-lint (or the wider ansible-dev-tools package) and run it from the project folder:
ansible-lint site.yml When we ran it on the freshly generated role, it flagged the placeholder author and company in meta/main.yml, a numeric min_ansible_version that should be a string, and the unprefixed http_port variable. After filling in meta/main.yml and renaming the variable, the project passed with zero failures at the strictest built-in profile, production.
Playbook building blocks at a glance
| Concept | What it is | Where it lives in this project |
|---|---|---|
| Inventory | The hosts and groups Ansible manages | inventory.ini |
| Play | A set of tasks mapped to a group of hosts | The top-level list item in site.yml |
| Task | One call to a module with arguments | roles/webserver/tasks/main.yml |
| Module | The unit of work, such as apt, template or service | Shipped in collections like ansible.builtin |
| Handler | A task that runs only when notified, once per play | roles/webserver/handlers/main.yml |
| Variables | Data that changes between hosts or environments | group_vars/web.yml, role defaults |
| Role | A reusable bundle of tasks, handlers, templates and defaults | roles/webserver/ |
Where to go after your first playbook
- Secrets: never put passwords in plain YAML.
ansible-vault create,ansible-vault encryptandansible-vault encrypt_stringkeep them encrypted in Git, andansible-playbook --ask-vault-pass site.ymldecrypts them at run time. - Collections: many useful modules live outside ansible.builtin. The firewall module for Ubuntu, for example, is
community.general.ufw, installed withansible-galaxy collection install community.generalif you use ansible-core alone. - Testing: Molecule is the Ansible testing framework for roles, playbooks and collections, and it pairs well with ansible-lint in CI.
- Running at scale: ansible-builder packages Ansible, collections and dependencies into container images called execution environments, and ansible-navigator runs and inspects content inside them.
- Provisioning: Ansible configures servers; tools like Terraform create them. Our Terraform tutorial for beginners shows that side, and the two are often used together.
Ansible is also a frequent topic in DevOps interviews alongside containers and orchestration; our Kubernetes interview questions and Puppet interview questions cover neighbouring tools you are likely to be asked about.
Learn Ansible with live, instructor-led training
Our Ansible training takes you from first playbooks to roles, Vault, Molecule testing and execution environments in live online classes with hands-on labs. Book a free demo to meet the trainer and see the syllabus, or browse all our courses, including Terraform and Docker.
Frequently asked questions
What is an Ansible playbook?
A playbook is a YAML file containing one or more plays. Each play selects hosts from the inventory and runs an ordered list of tasks against them, and each task uses a module to reach a desired state, such as a package being present or a service running.
What is the difference between an Ansible playbook and a role?
A playbook is what you run. A role is a reusable package of tasks, handlers, templates, files and default variables with a fixed folder structure. Playbooks call roles, so one role can serve many playbooks and projects.
Is Ansible easy to learn for beginners?
Ansible is one of the gentler automation tools to start with because playbooks are YAML rather than a programming language and nothing has to be installed on managed nodes. The harder parts are Linux administration itself, variable precedence and designing roles that stay idempotent.
Is Ansible free?
Yes. ansible-core is open source under the GNU General Public License v3.0, and the community ansible package is free to install. Red Hat Ansible Automation Platform is a separate commercial subscription built around the open source tools.
Can Ansible manage Windows servers?
Yes. Ansible manages Windows hosts with PowerShell-based modules, and the current release supports PowerShell 5.1 through 7 on Windows targets. The control node itself must still run Linux, macOS or WSL.
Sources
- Ansible documentation: Installing Ansible
- Ansible documentation: Releases and maintenance
- Ansible documentation: Getting started
- Ansible documentation: Ansible playbooks
- Ansible documentation: Handlers
- Ansible documentation: Using variables
- Ansible documentation: Roles
- Ansible documentation: Protecting sensitive data with Ansible Vault
- ansible.builtin.apt module
- Ansible Lint documentation
- Molecule documentation
- ansible/ansible on GitHub (licence)