Ravindra BagaleCourses & study guides मराठी

Chapter 11: Ansible Introduction

DevOps

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.
Check the syntax List the tasks Dry run Run for real Test from your laptop Run again Run more verbose when stuck
Playbook run: from your laptop to a working page

How: step by step

  1. Check the syntax

    ansible-playbook playbooks/web_welcome.yml --syntax-check
    

    What it does: Catches YAML mistakes before touching servers.

    Output

    playbook: playbooks/web_welcome.yml
    
  2. List the tasks

    ansible-playbook playbooks/web_welcome.yml --list-tasks
    

    What 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
    
  3. Dry run

    ansible-playbook playbooks/web_welcome.yml --check --diff
    

    What it does: Shows what would change.

    Output

    --- before: /var/www/html/index.html
    +++ after
    +<h1>Badge API is up</h1><p>web1</p>
    
  4. Run for real

    ansible-playbook playbooks/web_welcome.yml
    

    What 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
    
  5. Test from your laptop

    curl -s http://10.0.1.11
    

    What it does: The page shows the host name.

    Output

    <h1>Badge API is up</h1><p>web1</p>
    
  6. Run again

    ansible-playbook playbooks/web_welcome.yml
    

    What it does: Second run must be quiet.

    Output

    web1 : ok=4 changed=0 unreachable=0 failed=0
    
  7. Run more verbose when stuck

    ansible-playbook playbooks/web_welcome.yml -v
    

    What 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?

  1. Page works

    curl -s -o /dev/null -w "%{http_code}\n" http://10.0.1.12
    

    What it does: Expect 200.

    Output

    200
    
  2. Service enabled

    ansible web -a "systemctl is-enabled nginx"
    

    What it does: Starts after reboot.

    Output

    web1 | CHANGED | rc=0 >>
    enabled
    
  3. Quiet second run

    ansible-playbook playbooks/web_welcome.yml | tail -3
    

    What 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

  1. Line up keys under the module name.
  2. Never use tabs.
  3. 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

  1. Wait a minute and run again.
  2. 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

  1. ansible web -a "systemctl status nginx"
  2. Open port 80 in the security group for your IP.

Cleanup

  1. Stop the demo services

    ansible web -m service -a "name=badge-api state=stopped enabled=false" --become
    

    What 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.

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".

How:
  1. 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.

How:
  1. Add one copy task.
  2. 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.

How:
  1. Write the problem it solves.
  2. Write the one command or file you use for it.
  3. 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.

How:
  1. python3 -m pip install --user ansible-core
  2. docker run -d --name web1 -p 2221:22 lscr.io/linuxserver/openssh-server
  3. docker run -d --name web2 -p 2222:22 lscr.io/linuxserver/openssh-server
  4. 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.

How:
  1. If you used containers, use one EC2 or local VM now.
  2. Change only the inventory file.
  3. 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.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. 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.

How:
  1. Run once and note changed=.
  2. Run again with no edits.
  3. 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.

How:
  1. 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.

How:
  1. 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.

How:
  1. 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

  1. Explain the structure of a playbook.

    A list of plays. Each play has hosts, optional become and vars, and tasks that call modules.

  2. How do you test a playbook safely?

    syntax-check, then --check --diff on staging, then a real run on staging, then prod.

  3. 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.

  4. How do you pass a variable at run time?

    With -e name=value. Extra vars have the highest priority.

  5. 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.

Ravi Sir's Cards for this lesson

मराठी cards