CI/CD and automation · Intermediate · 18 min
How to Configure a Server with an Ansible Playbook
By Padding · Updated 15 Nov 2026
Ubuntu 26.04.1 LTS · Ansible 14 (ansible-core 2.21)
You will install Ansible 14 on your own computer, describe a web server's setup in a playbook, apply it over SSH, run it a second time to see that nothing changes, and preview a change with check mode before applying it.
On this page
Setting up a server by hand works once. The second server takes the same hour, and the tenth drifts: one has a package the others lack, one is missing a setting you changed last month. Ansible replaces the hand work with a file. You describe the state you want, "Nginx is installed, this page is served, the service is running", and Ansible connects over SSH and changes only what differs.
Nothing is installed on the servers you manage. Ansible uses the SSH and Python they already have. In this tutorial you will write a playbook for a small web server, apply it, and learn the two habits that make Ansible safe: run it twice, and preview changes first.
Step 1 · Install Ansible
Ubuntu's own ansible package is an older release. The current one comes from PyPI, and the simplest safe way to install a Python program is pipx, which gives each program its own virtual environment. The ansible package includes ansible-core and a large set of community collections. Pin the version so your results match this tutorial:
sudo apt update
sudo apt install -y pipx openssh-client
pipx install --include-deps ansible==14.6.0
export PATH="$HOME/.local/bin:$PATH"
ansible --version | head -n 1--include-deps makes pipx expose the commands of the packages ansible depends on, including ansible-playbook, which belongs to ansible-core. The last line prints ansible [core 2.21. followed by a patch number. Add the PATH line to ~/.bashrc (or run pipx ensurepath and open a new terminal) so the commands are always found. To upgrade later, run pipx upgrade ansible; the pin above is only for this tutorial. This install does not receive updates from apt.
Troubleshooting
pipx: command not foundafter the install: open a new terminal, or runsudo apt install -y pipxagain and check for errors.ansible-playbook: command not found: the install usedpipx install ansiblewithout--include-deps, or~/.local/binis not on your PATH. Reinstall with the flag and fix the PATH.
Step 2 · Describe your servers in an inventory
The inventory lists the machines Ansible manages, in groups. Make a project folder, and write an INI-style inventory with one group called web. Replace the address and the user with your server's. The user must be one that can log in with your SSH key and use sudo:
mkdir ansible-demo
cd ansible-demo
cat > inventory.ini <<'INI'
[web]
web1 ansible_host=203.0.113.10
[web:vars]
ansible_user=deploy
INI
export WEB_HOST=203.0.113.10 # the same address, used by the curl checks belowweb1 is a name you choose for the machine, and ansible_host is the address to connect to. 203.0.113.10 is a documentation address and will not work. [web:vars] sets variables for every host in the group.
Connect with SSH to the server once by hand, so that you accept its host key and know the key login works. Ansible uses your normal SSH settings and keys, so anything that works with ssh works here. See /tutorials/log-in-to-a-server-with-ssh-keys if that part is not in place. Then ask Ansible to reach every host in the web group. The ping module is not a network ping: it logs in and checks that Python runs:
ansible web -i inventory.ini -m pingEach host prints SUCCESS and "ping": "pong". A UNREACHABLE! result means SSH failed, and the message holds the SSH error. Fix it with plain ssh first.
Step 3 · Write a playbook
A playbook is a YAML file of plays. Each play picks hosts and lists tasks. Each task calls a module with arguments. This one installs Nginx, writes a page from a template, and keeps the service running:
mkdir templates
cat > templates/index.html.j2 <<'HTML'
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{{ site_title }}</title></head>
<body>
<h1>{{ site_title }}</h1>
<p>Configured by Ansible on {{ inventory_hostname }}.</p>
</body>
</html>
HTML
cat > site.yml <<'YAML'
- name: Set up the web server
hosts: web
become: true
vars:
site_title: Hello from Ansible
tasks:
- name: Install Nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600
- name: Write the home page
ansible.builtin.template:
src: templates/index.html.j2
dest: /var/www/html/index.html
owner: root
group: root
mode: "0644"
notify: Reload Nginx
- name: Make sure Nginx is running and starts at boot
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Reload Nginx
ansible.builtin.service:
name: nginx
state: reloaded
YAMLThe pieces:
hosts: webapplies the play to the inventory group.become: trueruns the tasks withsudo. If your user needs a password forsudo, add--ask-become-pass(or-K) to the command. Passwordless sudo is common for automation users, but it is a decision about that user's rights, so make it knowingly.- Modules are named in full, such as
ansible.builtin.apt. Short names work, but full names avoid clashes with collections. state: presentdescribes an end state, not an action. If Nginx is installed, the task does nothing. That is the idea behind idempotence.ansible.builtin.templaterenders the Jinja2 file on the control machine, replacing{{ site_title }}with the variable, and copies the result.notifytriggers a handler, and handlers run once at the end of the play, only if a task that notified them changed something. Here the handler reloads Nginx only when the page changed.
Before running it, check the syntax. This does not connect to anything:
ansible-playbook -i inventory.ini site.yml --syntax-checkIt prints playbook: site.yml.
Step 4 · Apply the playbook
Run it for real:
ansible-playbook -i inventory.ini site.ymlAnsible may print a warning that it discovered the Python interpreter at /usr/bin/python3.x and that installing another one later could change the choice. It is harmless; set ansible_python_interpreter=/usr/bin/python3 on the host line to pin it and silence it. Ansible prints each task, with ok for no change and changed for a change. The first run shows changed for the install and the page, and for the handler that reloads Nginx at the end. On Ubuntu, installing the Nginx package also starts the service, so the task that makes sure it is running usually reports ok, and the recap reads something like ok=5 changed=3 failed=0. The exact numbers depend on the server's starting state, and a server where Nginx was installed but stopped shows one more changed. Read the recap: failed=0 and unreachable=0 are what you want. Everything else is detail.
Check it worked
curl -s "http://$WEB_HOST/" | head -n 6WEB_HOST holds the address from your inventory. This needs the server's firewall to allow port 80; if it does not, run the same curl on the server itself against http://127.0.0.1/. The page shows the heading Hello from Ansible and the server name web1.
Troubleshooting
Missing sudo password: the user needs a password forsudo. Add--ask-become-pass.Failed to connect to the host via ssh: Permission denied (publickey): the key Ansible used is not authorised for that user. Setansible_ssh_private_key_file=~/.ssh/your_keyon the host line, or fix the key as in/tutorials/log-in-to-a-server-with-ssh-keys.Could not get lock /var/lib/dpkg/lock-frontend: another apt process, such as the unattended upgrade at boot, holds the lock. Wait a minute and run again.Host key verification failed: connect once withsshand accept the host key, after checking its fingerprint.
Step 5 · Run it again, and preview changes
Run the same command a second time:
ansible-playbook -i inventory.ini site.ymlThe recap now reads ok=4 changed=0. Nothing was reinstalled and nothing was rewritten, because the server already matches the playbook. A playbook you can safely run any number of times is one you can run from a schedule or a pipeline.
Now change something in the template, and preview the effect. --check makes Ansible report what it would change without changing it, and --diff shows the file differences:
sed -i 's/Configured by Ansible/Managed by Ansible/' templates/index.html.j2
ansible-playbook -i inventory.ini site.yml --check --diffThe output shows the old and new lines of index.html with a - and +, and the recap counts the page task and the reload handler as changes (changed=2). The server is untouched; confirm with curl, which still returns the old wording:
curl -s "http://$WEB_HOST/" | grep -c "Configured by"Check mode is a good habit before any real run on a server that matters. It is not a perfect prediction: tasks that depend on the result of an earlier command can be skipped or approximated. Apply the change:
ansible-playbook -i inventory.ini site.yml
curl -s "http://$WEB_HOST/" | grep "Managed by"The page now says Managed by Ansible, and the handler reloaded Nginx. Keep the playbook in Git, and review changes to it like code. Never put passwords in it. Use Ansible Vault (ansible-vault) for secrets, and prompt for them rather than passing them on the command line.
Step 6 · Undo what you did
Ansible does not remove things by itself. Describe the opposite state, and apply it. The next command stops Nginx, uninstalls it, and deletes the page this playbook wrote (uninstalling a package does not remove files you added yourself). Use it only on the demo server:
cat > cleanup.yml <<'YAML'
- name: Remove the demo web server
hosts: web
become: true
tasks:
- name: Stop Nginx
ansible.builtin.service:
name: nginx
state: stopped
- name: Uninstall Nginx
ansible.builtin.apt:
name: nginx
state: absent
purge: true
autoremove: true
- name: Remove the page this playbook wrote
ansible.builtin.file:
path: /var/www/html/index.html
state: absent
YAML
ansible-playbook -i inventory.ini cleanup.ymlThe recap shows failed=0. Remove the project folder with rm -rf ansible-demo when you are finished, and remove Ansible with pipx uninstall ansible.
Next steps
- Understand the server you are configuring:
/tutorials/install-nginx-on-ubuntu-26-04. - Create the sudo user Ansible logs in as:
/tutorials/create-a-sudo-user-on-ubuntu-26-04. - Run your playbook from a pipeline:
/tutorials/deploy-to-a-server-over-ssh-with-github-actions. - The documentation is at docs.ansible.com/projects/ansible/latest/ (playbook guide and module index).
Related tutorials
- How to Log In to a Linux Server with SSH KeysYou will create an Ed25519 SSH key, install its public half on a server, log in without a password, and save the connection as a short name.
- How to Install Nginx on Ubuntu 26.04You will install the current stable Nginx 1.30 from the official nginx.org repository on Ubuntu 26.04, serve its test page, and learn where its files live and how to reload it safely.
- How to Create a Sudo User on Ubuntu 26.04You will create a user that can run administrative commands with sudo, test it, limit it to specific commands, and take the access away again.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials