Ravindra BagaleCourses & study guides मराठी

Chapter 11: Ansible Introduction

DevOps

11.12 Lab — playbook installs Nginx welcome

Why: the problem

Suppose we are at Swiggy and a new office needs a simple welcome page on a fresh server, today, and again next week on ten more. Doing it by hand means SSH, apt, copy, restart, ten times, with typos. In this lab you do it once with Ansible: ping, playbook, curl, and a second run that changes nothing. This is the whole chapter in one hour.

What we will build

You will build the badge API welcome lab end to end: inventory, ping, a playbook that installs nginx, drops index.html, enables the service, then curl it and run it again to prove idempotence. Then you turn it into a role and run it on a second stack.

What: every term in plain English

  • Lab host — A throwaway VM or container you can SSH into.
  • badge-api_web — The inventory group for this lab.
  • Welcome page — A simple index.html that nginx serves.
  • Idempotence proof — Second run shows changed=0.
  • Role — The same tasks moved into roles/web_welcome.
  • curl — A command to fetch the page and check the result.
Write the inventory Ping it Check the playbook Dry run Real run Curl the page Run again
Lab: inventory, ping, playbook, curl, run again

How: step by step

  1. Write the inventory

    printf "[badge-api_web]\nlab1 ansible_host=10.0.1.11 ansible_user=ubuntu\n" > inventory/hosts.ini
    

    What it does: One host in the lab group.

    Output

    (no output)
    
  2. Ping it

    ansible badge-api_web -m ping
    

    What it does: pong.

    Output

    lab1 | SUCCESS => {"ping": "pong"}
    
  3. Check the playbook

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

    What it does: No errors.

    Output

    playbook: playbooks/web_welcome.yml
    
  4. Dry run

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

    What it does: See planned changes.

    Output

    lab1 : ok=4 changed=3 failed=0
    
  5. Real run

    ansible-playbook playbooks/web_welcome.yml
    

    What it does: Installs and serves.

    Output

    lab1 : ok=5 changed=3 unreachable=0 failed=0
    
  6. Curl the page

    curl -s http://10.0.1.11 | head -3
    

    What it does: Welcome text.

    Output

    <h1>Welcome to badge API</h1>
    
  7. Run again

    ansible-playbook playbooks/web_welcome.yml
    

    What it does: Idempotent.

    Output

    lab1 : ok=5 changed=0 unreachable=0 failed=0
    

Example 1: The lab playbook for Ubuntu and nginx

Stack. Ubuntu 22.04, nginx

Goal. The lab playbook for Ubuntu and nginx.

playbooks/web_welcome.yml

- name: Badge API welcome page
  hosts: badge-api_web
  become: true
  vars:
    welcome_title: "Welcome to badge API"
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600
    - name: Welcome page
      ansible.builtin.copy:
        dest: /var/www/html/index.html
        content: |
          <h1>{{ welcome_title }}</h1>
          <p>Served by {{ inventory_hostname }}</p>
      notify: Reload nginx
    - name: nginx running and enabled
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

What each line does

  • cache_valid_time — Skip apt update if done in the last hour.
  • content: | — Write the file from the playbook.
  • notify — Reload only when the page changes.

Green output

PLAY [Badge API welcome page] **************************
TASK [Install nginx] ***********************************
changed: [lab1]
TASK [Welcome page] ************************************
changed: [lab1]
TASK [nginx running and enabled] ***********************
ok: [lab1]
RUNNING HANDLER [Reload nginx] *************************
changed: [lab1]
PLAY RECAP *********************************************
lab1 : ok=5 changed=3 unreachable=0 failed=0

Expected result. First run changes three things; the second run changes none.

Example 2: Same lab as a role, called from a short playbook

Stack. Ansible roles

Goal. Same lab as a role, called from a short playbook.

roles/web_welcome/tasks/main.yml

- name: Install nginx
  ansible.builtin.apt: { name: nginx, state: present, update_cache: true, cache_valid_time: 3600 }
- name: Welcome page
  ansible.builtin.template: { src: index.html.j2, dest: /var/www/html/index.html }
  notify: Reload nginx
- name: nginx running
  ansible.builtin.service: { name: nginx, state: started, enabled: true }

roles/web_welcome/handlers/main.yml

- name: Reload nginx
  ansible.builtin.service: { name: nginx, state: reloaded }

playbooks/web_welcome_role.yml

- hosts: badge-api_web
  become: true
  roles:
    - web_welcome

What each line does

  • template — index.html.j2 can use variables.
  • roles: [web_welcome] — The playbook is now three lines.

Green output

$ ansible-playbook playbooks/web_welcome_role.yml
TASK [web_welcome : Install nginx] *****
ok: [lab1]
TASK [web_welcome : Welcome page] ******
ok: [lab1]
PLAY RECAP *****************************
lab1 : ok=3 changed=0 unreachable=0 failed=0

Expected result. The role gives the same result, so changed=0.

Example 3: Second stack: nginx in front of a Python Flask badge API

Stack. Python Flask, gunicorn, nginx

Goal. Second stack: nginx in front of a Python Flask badge API.

roles/flask_api/tasks/main.yml

- name: Python packages
  ansible.builtin.apt: { name: [python3-venv, python3-pip], state: present }
- name: App folder
  ansible.builtin.file: { path: /opt/badge, state: directory, owner: ubuntu }
- name: App code
  ansible.builtin.copy: { src: app.py, dest: /opt/badge/app.py }
  notify: Restart badge
- name: venv with flask and gunicorn
  ansible.builtin.pip: { name: [flask, gunicorn], virtualenv: /opt/badge/venv, virtualenv_command: python3 -m venv }
- name: systemd unit
  ansible.builtin.copy:
    dest: /etc/systemd/system/badge.service
    content: |
      [Service]
      WorkingDirectory=/opt/badge
      ExecStart=/opt/badge/venv/bin/gunicorn -b 127.0.0.1:5000 app:app
      Environment=BADGE_SECRET={{ lookup('env', 'BADGE_SECRET') | default('CHANGE_ME', true) }}
      [Install]
      WantedBy=multi-user.target
  notify: Restart badge
- name: badge running
  ansible.builtin.systemd: { name: badge, state: started, enabled: true, daemon_reload: true }

roles/flask_api/files/app.py

from flask import Flask
app = Flask(__name__)
@app.get("/api/badge")
def badge():
    return {"status": "ok", "name": "badge-api"}

What each line does

  • virtualenv — Python packages go in their own folder.
  • gunicorn — Runs Flask on port 5000 behind nginx.
  • lookup('env','BADGE_SECRET') — Secret comes from the environment.

Green output

$ curl -s http://10.0.1.11/api/badge
{"name":"badge-api","status":"ok"}
$ ansible-playbook playbooks/badge_api.yml | tail -1
lab1 : ok=9 changed=0 unreachable=0 failed=0

Expected result. The welcome page and the API run on the same server.

Example 4: Third stack: run the same role on a Docker lab container

Stack. Docker container as lab host

Goal. Third stack: run the same role on a Docker lab container.

terminal

docker run -d --name lab2 -p 8081:80 -p 2222:22 ubuntu-ssh-lab:22.04
printf "lab2 ansible_host=127.0.0.1 ansible_port=2222 ansible_user=lab\n" >> inventory/hosts.ini
ansible-playbook playbooks/web_welcome_role.yml --limit lab2
curl -s http://localhost:8081

What each line does

  • -p 2222:22 — SSH into the container on port 2222.
  • --limit lab2 — Only the new host.

Green output

lab2 : ok=4 changed=3 unreachable=0 failed=0
<h1>Welcome to badge API</h1>
<p>Served by lab2</p>

Expected result. Same role, a different target, no change to the playbook.

Verify: did it work?

  1. Page served

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

    What it does: 200

    Output

    200
    
  2. Second run

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

    What it does: changed=0.

    Output

    lab1 : ok=5 changed=0 unreachable=0 failed=0
    
  3. Service enabled

    ansible badge-api_web -a "systemctl is-enabled nginx"
    

    What it does: enabled.

    Output

    lab1 | CHANGED | rc=0 >>
    enabled
    

When it is red 1

curl: (7) Failed to connect to 10.0.1.11 port 80: Connection refused

Cause. nginx not running, or a firewall or security group blocks port 80.

Fix, step by step

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

When it is red 2

fatal: [lab1]: FAILED! => {"msg": "Missing sudo password"}

Cause. become needs a password for this user.

Fix, step by step

  1. Run with -K.
  2. Or use the cloud default user that has sudo without a password.

When it is red 3

Second run shows changed=1 for Welcome page

Cause. The content has something that changes every run, like a date.

Fix, step by step

  1. Remove time stamps from the page.
  2. Use facts that do not change.

Cleanup

  1. Remove the lab

    ansible badge-api_web -b -m apt -a "name=nginx state=absent purge=true"; docker rm -f lab2
    

    What it does: Lab cleaned.

    Output

    lab1 | CHANGED => {"changed": true}
    lab2
    

Ravindra Bagale's Tip

Finish the lab: curl and a second run with changed=0. That is the proof.

Practice tasks

Easy Finish the lab

Why: Prove the full flow.

What to do: Run all seven steps.

How:
  1. Follow the numbered steps.

Check: curl shows the page and second run is changed=0.

Medium Convert to a role

Why: Reuse.

What to do: Move tasks into roles/web_welcome.

How:
  1. Use ansible-galaxy init roles/web_welcome.

Check: Role run is green.

Easy Say welcome lab 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 welcome lab 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, finish this lab on one cloud VM and one Docker container, take a screenshot of curl and of the second run recap, and commit only the example inventory.

Recap

  • Inventory, ping, playbook, curl, run again.
  • Handlers reload only on change.
  • A role makes the playbook three lines.
  • The same role works on VM and container.
  • Commit only the example inventory.

FAQ

Can I use Amazon Linux?

Yes, use dnf in place of apt, or the package module.

Why cache_valid_time?

So apt update is not run every time.

Do I need a domain?

No, use the IP for the lab.

Why not run nginx in Docker?

You can; here we practice managing a server.

What if port 80 is used?

Stop the other service or change the nginx listen port.

Interview questions

  1. Walk me through a playbook you wrote.

    Inventory group, install nginx, copy page, service enabled, handler reload, then proof with curl and changed=0.

  2. How do you prove a playbook is idempotent?

    Run it twice; the second recap must show changed=0.

  3. When do you turn tasks into a role?

    When they are reused or the playbook grows big.

  4. How do you test on many OSes?

    Containers or Molecule with several images.

  5. How do you avoid leaking lab IPs?

    Commit a sanitized example inventory only.

Quick quiz

Q1. Which group is used in this lab?

badge-api_web

Q2. What proves idempotence?

changed=0 on the second run.

Q3. Which module writes the page?

copy or template

Q4. What reloads nginx only on change?

A handler with notify.

Q5. How do you run only on lab2?

--limit lab2

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards