Skip to content

Write your first Ansible playbook: a step-by-step guide

Start from an empty directory and finish with a working playbook: install Ansible, write an inventory, ping a host, install and configure Nginx, then re-run it and watch changed=0. Every command shows its real output.

An Ansible playbook is a YAML file that describes the state you want a server to be in — this package installed, this file present with these contents, this service running — and Ansible makes the server match that description. It runs from your own machine over SSH, so there is nothing to install on the server itself. By the end of this page you will have three small files in one directory, a real Nginx server configured by them, and two runs of the same playbook behind you: the first reporting changed=4, the second reporting changed=0. That second number is the entire reason people use Ansible instead of a shell script.

What you’ll accomplish

  • One inventory.ini listing a single target host, and a three-line ansible.cfg so you stop typing -i on every command.
  • A successful ansible all -m ansible.builtin.ping, which proves SSH and Python are in place before you write any YAML.
  • One site.yml playbook that installs Nginx, writes a landing page, deploys a config file, and keeps the service running.
  • A handler that reloads Nginx only when the config file actually changed — and you will watch it fire, then watch it stay quiet.
  • A second run of the identical command reporting changed=0. That is idempotency, and it is the moment Ansible starts being useful.

Prerequisites

  • Ansible. This guide describes ansible-core 2.16 or newer, on Python 3.10 or newer. Everything here also works with the larger ansible package, which is ansible-core plus several hundred bundled collections.
  • A control machine. Your laptop, a small VM, a jump box — anything that runs Python 3 and can open an SSH connection. Windows users should work from WSL; Ansible does not run as a control node on native Windows.
  • One target host you are allowed to break. A fresh Ubuntu 22.04 or 24.04 VM is ideal. This guide uses Debian-family package commands.
  • SSH key access to that host as a user who can sudo. Confirm it by hand first: ssh deploy@web1.example.com should land you at a prompt without asking for a password.
  • Python 3 on the target. Ubuntu and Debian server images already have it.

That last point is worth stating plainly, because it is the thing beginners most often get wrong: Ansible runs entirely from your machine. There is no agent, no daemon, no package to install on the servers you are managing. For each task, Ansible copies a small Python program to the target over SSH, runs it, collects the result as JSON, and deletes it. If you can SSH to a box and Python 3 is present, Ansible can manage it today.

How it works

Four pieces do all the work. The control node is your machine, where ansible-playbook runs. The inventory is a plain text file listing the hosts and putting them into groups. Modules are the units of work — ansible.builtin.apt, ansible.builtin.copy, ansible.builtin.systemd_service — and each one is pushed to the target and run there. The playbook binds a group of hosts to an ordered list of tasks.

Diagram showing the Ansible control node reading an inventory and a playbook, then pushing modules over SSH to three target hosts that have only Python installed

Two ideas separate a playbook from a shell script.

The first is idempotency. A module is written to describe an end state, not an action. ansible.builtin.apt with state: present checks whether the package is installed and only installs it if it is missing. ansible.builtin.copy hashes the destination file and only writes if the contents differ. So a task reports changed only when it genuinely modified something, and running the playbook against an already-correct host does nothing at all. That is what makes it safe to run the same playbook every day.

The second is handlers. A handler is a task that is held back and executed only if something notified it, and only once, at the end of the play, no matter how many tasks notified it. This is how you express “reload Nginx, but only if the config actually changed”. A task that reports ok notifies nothing; a task that reports changed triggers its handler. Get this right and you stop restarting services for no reason.

Step-by-step

  1. Install Ansible on your machine. Use a virtualenv so the version is yours to control and system Python stays clean.

    python3 -m venv ~/.venvs/ansible
    ~/.venvs/ansible/bin/pip install --upgrade pip ansible-core
    export PATH="$HOME/.venvs/ansible/bin:$PATH"
    ansible --version

    Expected output — the version number will differ, but every line should be present:

    ansible [core 2.18.6]
      config file = None
      configured module search path = ['/home/deploy/.ansible/plugins/modules']
      ansible python module location = /home/deploy/.venvs/ansible/lib/python3.12/site-packages/ansible
      ansible collection location = /home/deploy/.ansible/collections
      executable location = /home/deploy/.venvs/ansible/bin/ansible
      python version = 3.12.3
      jinja version = 3.1.6
      libyaml = True
  2. Create the project directory, the inventory, and a config file. Three files, one directory, no framework.

    mkdir -p ~/ansible-first && cd ~/ansible-first
    # inventory.ini
    [web]
    web1.example.com
    
    [web:vars]
    ansible_user=deploy
    # ansible.cfg
    [defaults]
    inventory = inventory.ini

    [web] declares a group named web with one host in it. [web:vars] sets the SSH username for every host in that group. The ansible.cfg in the current directory is picked up automatically, so from here on you can drop -i inventory.ini. Confirm Ansible sees the host:

    ansible-inventory --list --yaml
    all:
      children:
        web:
          hosts:
            web1.example.com:
              ansible_user: deploy
  3. Prove the connection before writing any YAML. The ping module does not send an ICMP packet — it connects over SSH, runs a tiny Python program, and asks it to answer. It tests the whole chain at once.

    ansible all -m ansible.builtin.ping
    web1.example.com | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": false,
        "ping": "pong"
    }

    Green SUCCESS and "ping": "pong" means SSH works, the user is right, and Python was found. If you get UNREACHABLE! instead, stop here and fix it — see the troubleshooting section. Writing a playbook against a host you cannot reach only produces confusing errors.

  4. Write the playbook. Keep the first one small. One play, four tasks, one handler.

    # site.yml
    - name: Web server baseline
      hosts: web
      become: true
    
      tasks:
        - name: Install Nginx
          ansible.builtin.apt:
            name: nginx
            state: present
            update_cache: true
    
        - name: Write the landing page
          ansible.builtin.copy:
            content: "Hello from Ansible\n"
            dest: /var/www/html/index.html
            owner: root
            group: root
            mode: '0644'
    
        - name: Deploy the site config
          ansible.builtin.copy:
            content: |
              server {
                  listen 8080 default_server;
                  root /var/www/html;
                  index index.html;
                  server_tokens off;
              }
            dest: /etc/nginx/conf.d/hello.conf
            owner: root
            group: root
            mode: '0644'
          notify: Reload Nginx
    
        - name: Ensure Nginx is enabled and running
          ansible.builtin.systemd_service:
            name: nginx
            enabled: true
            state: started
    
      handlers:
        - name: Reload Nginx
          ansible.builtin.systemd_service:
            name: nginx
            state: reloaded

    become: true means “use sudo for every task in this play”. The notify: Reload Nginx line has to match the handler’s name exactly, character for character — a typo there is silent, and the handler simply never runs. ansible.builtin.systemd_service is the current name of the systemd module; older material calls it ansible.builtin.systemd, which still works as an alias.

    Check the YAML parses before you go near a server:

    ansible-playbook site.yml --syntax-check
    playbook: site.yml
  5. Dry-run it with --check. Check mode runs every task in “predict, do not apply” mode. Add --diff to see the exact file contents Ansible would write.

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

    On a genuinely fresh host, expect this to stop partway through — and that is not a bug:

    TASK [Install Nginx] ***********************************************************
    changed: [web1.example.com]
    
    TASK [Write the landing page] **************************************************
    changed: [web1.example.com]
    
    TASK [Deploy the site config] **************************************************
    fatal: [web1.example.com]: FAILED! => {"changed": false, "msg": "Destination directory /etc/nginx/conf.d does not exist"}
    
    PLAY RECAP *********************************************************************
    web1.example.com  : ok=3  changed=2  unreachable=0  failed=1  skipped=0  rescued=0  ignored=0

    Nothing was installed, so /etc/nginx/conf.d/ does not exist yet, so the copy task cannot predict its own success. Check mode is a drift preview for a host that is already configured; on a blank host it will always trip over dependencies between tasks. Read it, then move on.

  6. Run it for real. No flags. This is the run that changes the server.

    ansible-playbook site.yml
    PLAY [Web server baseline] *****************************************************
    
    TASK [Gathering Facts] *********************************************************
    ok: [web1.example.com]
    
    TASK [Install Nginx] ***********************************************************
    changed: [web1.example.com]
    
    TASK [Write the landing page] **************************************************
    changed: [web1.example.com]
    
    TASK [Deploy the site config] **************************************************
    changed: [web1.example.com]
    
    TASK [Ensure Nginx is enabled and running] *************************************
    ok: [web1.example.com]
    
    RUNNING HANDLER [Reload Nginx] *************************************************
    changed: [web1.example.com]
    
    PLAY RECAP *********************************************************************
    web1.example.com  : ok=6  changed=4  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

    Read the recap carefully, because it is the report card for every run you will ever do. ok=6 counts every task that succeeded, including the changed ones and the automatic Gathering Facts step. changed=4 is three tasks plus the handler. The service task reported ok, not changed, because installing the Nginx package already started it — Ansible checked, found the desired state, and did nothing. And RUNNING HANDLER appears because the config task reported changed and notified it.

  7. Run it a second time. Same command, no arguments, no edits.

    ansible-playbook site.yml
    TASK [Deploy the site config] **************************************************
    ok: [web1.example.com]
    
    TASK [Ensure Nginx is enabled and running] *************************************
    ok: [web1.example.com]
    
    PLAY RECAP *********************************************************************
    web1.example.com  : ok=5  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

    changed=0, and the RUNNING HANDLER block is gone entirely — an un-notified handler does not appear in the output at all. Notice ok=5 rather than 6: the handler did not run, so it is not counted.

    Diagram comparing run one, where four tasks report changed and the handler fires, against run two, where every task reports ok, the handler does not run, and the recap shows changed=0

  8. Change one line and watch the handler come back. Edit site.yml and change listen 8080 to listen 8081, then run again.

    TASK [Deploy the site config] **************************************************
    changed: [web1.example.com]
    
    RUNNING HANDLER [Reload Nginx] *************************************************
    changed: [web1.example.com]
    
    PLAY RECAP *********************************************************************
    web1.example.com  : ok=6  changed=2  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

    One task changed, so the handler fired once. The other three tasks were already correct and stayed silent. Change the port back to 8080 before continuing.

Validate it works

Ask the target itself, using ad-hoc modules rather than SSH-ing in by hand:

ansible web -m ansible.builtin.uri -a 'url=http://localhost:8080/ return_content=true'
web1.example.com | SUCCESS => {
    "changed": false,
    "content": "Hello from Ansible\n",
    "content_type": "text/html",
    "status": 200
}

Then confirm the service state without touching it:

ansible web -b -m ansible.builtin.systemd_service -a 'name=nginx state=started'

A response of "changed": false means Nginx was already running and Ansible did nothing. Finally, run ansible-playbook site.yml one more time and confirm changed=0. A playbook that reports changed=0 on an unchanged host is a playbook you can safely put on a schedule.

Troubleshooting

The run hangs, then fails with UNREACHABLE! and “Host key verification failed”. Ansible does not run SSH interactively, so it cannot answer the “Are you sure you want to continue connecting?” prompt. SSH to the host once by hand to accept the key, or add it deliberately with ssh-keyscan web1.example.com >> ~/.ssh/known_hosts. Do not disable host key checking to make this go away — that removes the protection against a machine-in-the-middle on every future run.

"msg": "Missing sudo password". The task needs root, become: true is set, but your user’s sudo asks for a password. Either grant passwordless sudo for the deploy user, or pass --ask-become-pass (short form -K) so Ansible prompts you once at the start of the run. The error means Ansible reached the host and authenticated — SSH is fine.

ERROR! Syntax Error while loading YAML. did not find expected key. This is almost always indentation. YAML is whitespace-significant, tabs are illegal, and every key under a module must be indented consistently relative to the module name. The error message names a file, a line and a column: start there, and look at the line above the one reported, since that is usually where the wrong indent actually began. Set your editor to two-space soft tabs before you write more YAML.

Telling unreachable apart from failed. The recap counts them separately, and the difference decides where you look. unreachable=1 means Ansible never got a working connection — SSH, DNS, credentials, firewall, or Python missing on the target. Nothing on that host was touched. failed=1 means the connection worked and a task ran and returned an error — a wrong package name, a missing directory, a permission problem. Fix connection problems first; they make every downstream error meaningless.

A task reports changed on every single run. Nearly always a ansible.builtin.shell or ansible.builtin.command task. Those modules run whatever you give them and have no idea what “already done” means, so they report changed unconditionally. Replace them with a real module where one exists, and where one does not, add a creates: or removes: guard so Ansible can skip the command when the artifact already exists. A playbook that always reports changed cannot tell you anything, and it will fire your handlers — and restart your services — every run.

When this is the wrong approach

One host and one command is not a playbook. If you need to restart a service on a single box right now, SSH in and restart it. Ansible earns its keep when the same intent has to be applied repeatedly, or to more than one machine, or by more than one person.

Immutable infrastructure does not want a converging tool. If your servers are built from a machine image and replaced rather than modified, the configuration belongs in the image build, not in a playbook that repairs a running host. Ansible can build that image, but converging live production servers works against the model.

An application that already ships as a container image should be deployed as a container image. Writing a playbook that installs a runtime, clones a repository, and manages a systemd unit is rebuilding packaging that already exists. Use Ansible for the host underneath — kernel settings, users, storage, the container runtime itself — and let the image handle the application.

Once the playbook grows past roughly fifty tasks, stop adding to it and split it into roles with proper group_vars — that is covered in Ansible roles and inventory layout. Anything secret in those variables, including that first database password, should be encrypted before it reaches Git; see Ansible Vault for secrets. The module list at docs.ansible.com is the reference you will keep open, and the current documentation set tracks the version of ansible-core you just installed.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.