Chapter 11: Ansible Introduction
11.5 Playbook — Nginx welcome for badge API
Why: the problem
Suppose we are at Instagram and the badge API team needs a welcome page on every web server, so the load balancer health check passes. Ad-hoc commands worked once, but next week a new server arrives and nobody remembers the steps. A playbook is a saved recipe in YAML. It says which hosts, which user, and which tasks, in order. You put it in Git, review it, and run it for every new server.
What we will build
You will write web_welcome.yml that installs nginx, places a welcome page with the server name, and starts nginx. Then you will run the same idea for a Node.js API and for a Python Flask API behind nginx.
What: every term in plain English
- Play — One block in a playbook: a group of hosts and the tasks for them.
- Task — One step that calls one module, with a readable name.
- vars — Values you can reuse in tasks with {{ name }}.
- Jinja2 — The template language behind {{ }}.
- inventory_hostname — A built-in variable: the host name from the inventory.
- PLAY RECAP — The summary at the end: ok, changed, failed per host.
How: step by step
-
Check the syntax
ansible-playbook playbooks/web_welcome.yml --syntax-checkWhat it does: Catches YAML mistakes before touching servers.
Output
playbook: playbooks/web_welcome.yml -
List the tasks
ansible-playbook playbooks/web_welcome.yml --list-tasksWhat it does: See the order of work.
Output
play #1 (web): Nginx welcome page for badge API tasks: Install nginx Put the welcome page Nginx is running and starts on boot -
Dry run
ansible-playbook playbooks/web_welcome.yml --check --diffWhat it does: Shows what would change.
Output
--- before: /var/www/html/index.html +++ after +<h1>Badge API is up</h1><p>web1</p> -
Run for real
ansible-playbook playbooks/web_welcome.ymlWhat it does: Applies all tasks to all web hosts.
Output
PLAY RECAP web1 : ok=4 changed=3 unreachable=0 failed=0 web2 : ok=4 changed=3 unreachable=0 failed=0 -
Test from your laptop
curl -s http://10.0.1.11What it does: The page shows the host name.
Output
<h1>Badge API is up</h1><p>web1</p> -
Run again
ansible-playbook playbooks/web_welcome.ymlWhat it does: Second run must be quiet.
Output
web1 : ok=4 changed=0 unreachable=0 failed=0 -
Run more verbose when stuck
ansible-playbook playbooks/web_welcome.yml -vWhat it does: -v shows module results, -vvv shows SSH details.
Output
changed: [web1] => {"changed": true, "dest": "/var/www/html/index.html"}
Example 1: Static welcome page with nginx on Ubuntu
Stack. Ubuntu 22.04, nginx
Goal. Static welcome page with nginx on Ubuntu.
playbooks/web_welcome.yml
- name: Nginx welcome page for badge API
hosts: web
become: true
vars:
site_title: "Badge API is up"
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
- name: Put the welcome page
ansible.builtin.copy:
dest: /var/www/html/index.html
content: "<h1>{{ site_title }}</h1><p>{{ inventory_hostname }}</p>\n"
- name: Nginx is running and starts on boot
ansible.builtin.service:
name: nginx
state: started
enabled: true
What each line does
hosts: web— Run on the web group.vars: site_title— A value used inside the page.content:— Write this text into the file. No local file needed.enabled: true— Start nginx again after a reboot.
Green output
PLAY [Nginx welcome page for badge API] ****************
TASK [Gathering Facts] *********************************
ok: [web1]
ok: [web2]
TASK [Install nginx] ***********************************
changed: [web1]
changed: [web2]
TASK [Put the welcome page] ****************************
changed: [web1]
changed: [web2]
TASK [Nginx is running and starts on boot] *************
ok: [web1]
ok: [web2]
PLAY RECAP *********************************************
web1 : ok=4 changed=2 unreachable=0 failed=0
web2 : ok=4 changed=2 unreachable=0 failed=0
Expected result. Both servers serve a page that shows their own name.
Example 2: Node
Stack. Node.js 18, systemd, nginx
Goal. Node.js badge API as a systemd service behind nginx.
playbooks/node_api.yml
- name: Node badge API
hosts: web
become: true
vars:
app_dir: /opt/badge-api
tasks:
- name: Install Node.js and nginx
ansible.builtin.apt:
name: [nodejs, npm, nginx]
state: present
update_cache: true
- name: App folder
ansible.builtin.file:
path: "{{ app_dir }}"
state: directory
owner: www-data
- name: App code
ansible.builtin.copy:
dest: "{{ app_dir }}/server.js"
content: |
const http = require('http');
http.createServer((q, r) => r.end(JSON.stringify({badge: 'gold', host: process.env.HOSTNAME}))).listen(3000);
- name: systemd unit
ansible.builtin.copy:
dest: /etc/systemd/system/badge-api.service
content: |
[Unit]
Description=Badge API
[Service]
ExecStart=/usr/bin/node {{ app_dir }}/server.js
User=www-data
Restart=always
[Install]
WantedBy=multi-user.target
- name: Start the API
ansible.builtin.systemd:
name: badge-api
state: started
enabled: true
daemon_reload: true
- name: nginx proxies to port 3000
ansible.builtin.copy:
dest: /etc/nginx/sites-enabled/default
content: |
server { listen 80; location / { proxy_pass http://127.0.0.1:3000; } }
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
What each line does
content: |— Write a multi-line file inline.daemon_reload: true— Tell systemd to read the new unit file.proxy_pass— nginx forwards web traffic to Node on 3000.
Green output
$ ansible-playbook playbooks/node_api.yml
web1 : ok=8 changed=7 unreachable=0 failed=0
$ curl -s http://10.0.1.11
{"badge":"gold"}
Expected result. The API answers through nginx on port 80.
Example 3: Python Flask API with a virtualenv and gunicorn
Stack. Python 3, Flask, gunicorn
Goal. Python Flask API with a virtualenv and gunicorn.
playbooks/flask_api.yml
- name: Flask badge API
hosts: web
become: true
tasks:
- name: Python tools
ansible.builtin.apt:
name: [python3-venv, python3-pip]
state: present
- name: App code
ansible.builtin.copy:
dest: /opt/flask-badge/app.py
content: |
from flask import Flask
app = Flask(__name__)
@app.get("/")
def home():
return {"badge": "silver"}
- name: Python packages in a venv
ansible.builtin.pip:
name: [flask, gunicorn]
virtualenv: /opt/flask-badge/venv
virtualenv_command: python3 -m venv
- name: Run gunicorn as a service
ansible.builtin.copy:
dest: /etc/systemd/system/flask-badge.service
content: |
[Service]
WorkingDirectory=/opt/flask-badge
ExecStart=/opt/flask-badge/venv/bin/gunicorn -b 127.0.0.1:5000 app:app
Restart=always
[Install]
WantedBy=multi-user.target
- name: Start
ansible.builtin.systemd:
name: flask-badge
state: started
enabled: true
daemon_reload: true
What each line does
pip with virtualenv— Installs packages inside a venv, not system-wide.gunicorn -b 127.0.0.1:5000— Production web server for Flask, only local.
Green output
$ ansible web -a "curl -s localhost:5000"
web1 | CHANGED | rc=0 >>
{"badge":"silver"}
Expected result. Flask answers on port 5000 on each server.
Verify: did it work?
-
Page works
curl -s -o /dev/null -w "%{http_code}\n" http://10.0.1.12What it does: Expect 200.
Output
200 -
Service enabled
ansible web -a "systemctl is-enabled nginx"What it does: Starts after reboot.
Output
web1 | CHANGED | rc=0 >> enabled -
Quiet second run
ansible-playbook playbooks/web_welcome.yml | tail -3What it does: changed=0.
Output
web1 : ok=4 changed=0
When it is red 1
ERROR! Syntax Error while loading YAML.
mapping values are not allowed in this context
The offending line appears to be:
name: nginx
state: present
Cause. Wrong indentation. YAML uses spaces, two per level.
Fix, step by step
- Line up keys under the module name.
- Never use tabs.
- Run --syntax-check again.
When it is red 2
fatal: [web1]: FAILED! => {"msg": "Failed to lock apt for exclusive operation"}
Cause. Another apt process (often auto updates) is running.
Fix, step by step
- Wait a minute and run again.
- Or add lock_timeout: 120 to the apt task.
When it is red 3
curl: (7) Failed to connect to 10.0.1.11 port 80: Connection refused
Cause. nginx is not running, or a firewall blocks 80.
Fix, step by step
- ansible web -a "systemctl status nginx"
- Open port 80 in the security group for your IP.
Cleanup
-
Stop the demo services
ansible web -m service -a "name=badge-api state=stopped enabled=false" --becomeWhat it does: Free the lab.
Output
web1 | CHANGED => {"state": "stopped"}
Ravindra Bagale's Tip
Always start a playbook with --check --diff. You will see what will change before it changes.
Playbook ला नेहमी --check --diff ने सुरवात करा. काय बदलणार ते आधी दिसेल.
Playbook हमेशा --check --diff से शुरू करो. क्या बदलेगा पहले दिखेगा.
Practice tasks
Easy Change the title with -e
Why: Extra vars override play vars.
What to do: Run with -e site_title="Sale is live".
- ansible-playbook playbooks/web_welcome.yml -e site_title="Sale is live"
Check: curl shows the new title.
Medium Add a health page
Why: Load balancers need one.
What to do: Add /var/www/html/health with text ok.
- Add one copy task.
- Run and curl /health.
Check: curl /health prints ok.
Easy Say a playbook in two lines
Why: If you can say it simply, you understand it. Interviewers and juniors both need the short version first.
What to do: Write two short lines about a playbook for a fresher who knows only Linux basics.
- Write the problem it solves.
- Write the one command or file you use for it.
- Read it aloud to a friend.
Check: A fresher understands it without asking a question.
Easy Start a two-server Ansible lab
Why: Practice needs safe throwaway servers. If you break them, you delete them and start again in one minute.
What to do: Start two Ubuntu containers that accept SSH, and one control machine with Ansible.
- python3 -m pip install --user ansible-core
- docker run -d --name web1 -p 2221:22 lscr.io/linuxserver/openssh-server
- docker run -d --name web2 -p 2222:22 lscr.io/linuxserver/openssh-server
- ansible --version
Check: ansible --version prints a core version, and ssh to both ports works.
Medium Do it on the second setup
Why: The idea must work on a VM, a container and a cloud server. Only the inventory should change, never the playbook.
What to do: Repeat this lesson on a different target than the one you used first.
- If you used containers, use one EC2 or local VM now.
- Change only the inventory file.
- Run the same playbook.
Check: Same result, and you changed only the inventory.
Medium Break it on purpose
Why: You must know the red output by face. On a real outage there is no time to read slowly.
What to do: Cause one error from the "When it is red" part of this lesson and fix it.
- Follow the error section.
- Copy the exact message into your notes.
- Write the fix in one line.
Check: You fixed it using the steps, without searching the web.
Medium Run it twice and read the recap
Why: Idempotence is the heart of Ansible.
What to do: Run your playbook or command two times and compare the PLAY RECAP lines.
- Run once and note changed=.
- Run again with no edits.
- Explain any task that still says changed.
Check: The second run shows changed=0, or you can explain every change.
Medium Write a runbook page
Why: At 2 a.m. nobody remembers flags. A short written page saves the on-call person.
What to do: Write a one-page runbook for this lesson.
- Title, when to use, exact commands, how to check, how to undo.
Check: A teammate can follow it alone.
Hard Explain it like an interview
Why: Interviewers want real stories, not definitions.
What to do: Record a 60 second answer about this lesson.
- Say the problem, the playbook or command, and one error you hit.
Check: Your answer has a real command and a real error message.
Hard Draw the flow top to bottom
Why: A drawing shows the order of work.
What to do: Draw this lesson as boxes from top to bottom.
- Start at your laptop, go through SSH, end at the check on the server.
Check: Each box matches a real step you ran.
Homework: try at home
Try at home
At home, write a playbook that installs nginx, writes a page with your name and the server name, and starts nginx. Run it twice and curl both servers.
Recap
- A playbook has plays; a play has hosts and tasks.
- Use --syntax-check, --list-tasks and --check before a real run.
- Variables go in vars and are used with {{ }}.
- The same pattern deploys static, Node and Python apps.
- Second run must show changed=0.
FAQ
Can one playbook have many plays?
Yes, for example one for web and one for db.
Does order matter?
Yes. Tasks run top to bottom, on all hosts, one task at a time.
What if one host fails?
Ansible stops on that host and continues on others.
Where do playbooks live?
In Git, in a playbooks folder, next to the inventory.
Should content: hold big files?
No. Use copy with src or a template for big files.
Interview questions
-
Explain the structure of a playbook.
A list of plays. Each play has hosts, optional become and vars, and tasks that call modules.
-
How do you test a playbook safely?
syntax-check, then --check --diff on staging, then a real run on staging, then prod.
-
How does Ansible run tasks on many hosts?
Task by task. Each task runs on all hosts in parallel up to forks, then the next task.
-
How do you pass a variable at run time?
With -e name=value. Extra vars have the highest priority.
-
What is gather_facts?
The first step that collects host facts. You can turn it off with gather_facts: false to save time.
Quick quiz
Q1. What is a play?
A group of hosts plus the tasks for them.
Q2. How do you check YAML before running?
--syntax-check
Q3. What shows what would change?
--check --diff
Q4. What does inventory_hostname hold?
The host name from the inventory.
Q5. Why give every task a name?
The output becomes easy to read.
Did you understand? Let us try it once more.
Revision card
Interview card