πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

Ansible Playbooks are the heart of automation. They define what to do and how to do it β€” from provisioning servers to deploying applications.

Today’s focus is on mastering Ansible Playbooks: structure, syntax, modularity, variables, handlers, conditionals, loops, and roles.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ“–

πŸ’‘Learning points:

πŸ”Ή Anatomy of an Ansible Playbook
πŸ”Ή Using tasks, variables, conditionals, loops, and handlers
πŸ”Ή Structuring playbooks with includes and roles
πŸ”Ή Using facts and registered variables
πŸ”Ή Adding tags for targeted execution
πŸ”Ή Using when, loop, and block/rescue for better control
πŸ”Ή Writing idempotent playbooks (safe to run multiple times)
πŸ”Ή Debugging playbooks using ansible-playbook -vvv and debug module

🧠 Learn here:

Anatomy of an Ansible Playbook

An Ansible playbook is a YAML file that describes the desired state of your system. Basic structure includes:

- name: Install and configure web server
  hosts: webservers
  become: yes
  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present

Using Tasks, Variables, Conditionals, Loops, and Handlers

Tasks define what needs to be done.

- name: Install Nginx
  apt:
    name: nginx
    state: present

Variables provide dynamic data.

vars:
  web_package: nginx

Conditionals control execution.

when: ansible_os_family == 'Debian'

Loops repeat tasks.

loop:
  - nginx
  - git

Handlers respond to changes.

handlers:
  - name: restart nginx
    service:
      name: nginx
      state: restarted

Structuring Playbooks with Includes and Roles

Includes:

- import_tasks: install.yml

Roles (recommended structure for large projects):

roles/
β”œβ”€β”€ webserver/
β”‚   β”œβ”€β”€ tasks/main.yml
β”‚   β”œβ”€β”€ handlers/main.yml
β”‚   β”œβ”€β”€ templates/
β”‚   └── vars/main.yml

Using Facts and Registered Variables

Facts are auto-collected:

- debug:
    var: ansible_facts

Registered variables store command output:

- name: Check disk space
  command: df -h
  register: disk_usage

- debug:
    var: disk_usage.stdout_lines

Adding Tags for Targeted Execution

- name: Install nginx
  apt:
    name: nginx
    state: present
  tags: install

Run with:

ansible-playbook playbook.yml --tags install

Using when, loop, and block/rescue

when:

when: ansible_os_family == 'RedHat'

loop (the older with_items still works):

loop:
  - user1
  - user2

block/rescue:

- block:
    - name: Try something
      command: /bin/false
  rescue:
    - name: Recover
      debug:
        msg: "Command failed."

Writing Idempotent Playbooks

Ensure tasks don’t change anything if already in desired state.
Example:

- name: Create directory
  file:
    path: /etc/myapp
    state: directory

Debugging Playbooks

Use verbose mode:

ansible-playbook site.yml -vvv

Use the debug module:

- debug:
    msg: "The web server is {{ web_package }}"

πŸ”₯ Challenges

πŸ”Ή Challenge 1: Write a playbook to create multiple system users using a loop
πŸ”Ή Challenge 2: Add a debug task to print the output of uname -a
πŸ”Ή Challenge 3: Create a handler that restarts Nginx if a config file is changed
πŸ”Ή Challenge 4: Use when to run tasks only on certain operating systems
πŸ”Ή Challenge 5: Use tags to categorize tasks (install, config, restart)
πŸ”Ή Challenge 6: Refactor a playbook using include_tasks or import_tasks
πŸ”Ή Challenge 7: Create a main.yml file and use vars_files to separate configuration
πŸ”Ή Challenge 8: Set up a playbook that creates a user, installs a package, and starts a service β€” all in one run
πŸ”Ή Challenge 9: Add a rescue block to handle command failure gracefully
πŸ”Ή Challenge 10: Create a reusable playbook role structure manually (without ansible-galaxy)
πŸ”Ή Challenge 11: Set up a cron job using Ansible to schedule a periodic backup script.

πŸ”Ή Challenge 12: Write a playbook to deploy a web app with Git clone, package install, config setup, and service start.

πŸ”Ή Challenge 13: Configure firewall rules using Ansible (e.g., UFW on Ubuntu or firewalld on CentOS).

πŸ”Ή Challenge 14: Automate SSL certificate generation using Let’s Encrypt and deploy it to a web server.

πŸ”Ή Challenge 15: Use Ansible to template configuration files with jinja2 and deploy them to remote hosts.

πŸ”Ή Challenge 16: Deploy a multi-node application with dependencies (e.g., DB β†’ App Server β†’ Load Balancer).

πŸ”Ή Challenge 17: Create an Ansible role that can be reused across projects (e.g., a β€œcommon” role for all base configurations).


βœ… Solutions

πŸ”Ή Challenge 1: Write a playbook to create multiple system users using a loop

vars/users.yml

users:
  - name: alice
    comment: "Alice DevOps"
  - name: bob
    comment: "Bob Cloud Engineer"
  - name: charlie
    comment: "Charlie Platform Team"

create-multiple-users.yml

---
- name: Create multiple system users
  hosts: all
  become: yes
  vars_files:
    - vars/users.yml
  tasks:
    - name: Create system users in a loop
      ansible.builtin.user:
        name: "{{ item.name }}"
        comment: "{{ item.comment }}"
        shell: /bin/bash
        create_home: yes
        system: yes
      loop: "{{ users }}"

inventory.ini

[local]
localhost ansible_connection=local

▢️ Run the Playbook:

ansible-playbook -i inventory.ini create-multiple-users.yml


πŸ”Ή Challenge 2: Add a debug task to print the output of uname -a

debug-uname.yml

---
- name: Print system information with uname -a
  hosts: all
  become: false
  gather_facts: false
  tasks:
    - name: Run uname -a
      command: uname -a
      register: uname_output

    - name: Show uname output
      debug:
        msg: "{{ uname_output.stdout }}"

▢️ Run It

ansible-playbook -i inventory.ini debug-uname.yml

πŸ–₯️ Sample Output:

TASK [Show uname output] 
ok: [localhost] => {
    "msg": "Linux ip-172-31-16-100 5.15.0-1051-aws x86_64 GNU/Linux"
}

πŸ”Ή Challenge 3: Create a handler that restarts Nginx if a config file is changed

Directory Structure

.
β”œβ”€β”€ inventory.ini
β”œβ”€β”€ nginx-restart-handler.yml
└── files/
    └── nginx.conf

inventory.ini

[web]
localhost ansible_connection=local

files/nginx.conf

user www-data;   # Debian/Ubuntu; use "nginx" on RHEL/Amazon Linux
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
    worker_connections 1024;
}
http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log main;
    sendfile on;
    keepalive_timeout 65;
    include /etc/nginx/conf.d/*.conf;

    server {
        listen 80 default_server;
        server_name _;

        location / {
            root /usr/share/nginx/html;
            index index.html index.htm;
        }

        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
}

nginx-restart-handler.yml

---
- name: Apply Nginx config with handler
  hosts: web
  become: yes
  tasks:
    - name: Ensure Nginx is installed
      package:
        name: nginx
        state: present

    - name: Copy Nginx config file
      copy:
        src: files/nginx.conf
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: '0644'
        validate: nginx -t -c %s   # never restart with a broken config
      notify: Restart Nginx

    - name: Ensure Nginx is running and enabled
      service:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

▢️ Run the Playbook

ansible-playbook -i inventory.ini nginx-restart-handler.yml

πŸ”Ή Challenge 4: Use when to run tasks only on certain operating systems

install-nginx-by-os.yml

---
- name: Install Nginx based on OS
  hosts: all
  become: yes
  tasks:
    - name: Install Nginx on Ubuntu/Debian
      apt:
        name: nginx
        state: present
        update_cache: yes
      when: ansible_os_family == "Debian"

    - name: Install Nginx on Amazon Linux or RHEL
      yum:
        name: nginx
        state: present
      when: ansible_os_family in ["RedHat", "Amazon"]

    - name: Install Nginx on MacOS
      become: false   # Homebrew refuses to run as root
      community.general.homebrew:
        name: nginx
        state: present
      when: ansible_os_family == "Darwin"

    - name: Start Nginx on Linux
      service:
        name: nginx
        state: started
        enabled: yes
      when: ansible_os_family != "Darwin"

    - name: Start Nginx on MacOS using brew services
      become: false
      shell: brew services start nginx
      when: ansible_os_family == "Darwin"

▢️ Run the Playbook

ansible-playbook -i inventory.ini install-nginx-by-os.yml


πŸ”Ή Challenge 5: Use tags to categorize tasks (install, config, restart)

tagged-nginx-playbook.yml

---
- name: Categorized Nginx Deployment
  hosts: all
  become: yes
  tasks:
    - name: Install Nginx
      package:
        name: nginx
        state: present
      tags: install

    - name: Copy custom index.html
      copy:
        src: files/index.html
        dest: /var/www/html/index.html   # Ubuntu/Debian web root (RHEL: /usr/share/nginx/html)
        mode: '0644'
      notify: Restart Nginx
      tags: config

    - name: Ensure Nginx is running and enabled
      service:
        name: nginx
        state: started
        enabled: yes
      tags: restart

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

▢️ Run Specific Tags:

# Run only install-related tasks
ansible-playbook -i inventory.ini tagged-nginx-playbook.yml --tags install

# Run install + config
ansible-playbook -i inventory.ini tagged-nginx-playbook.yml --tags "install,config"

# Skip the restart tag
ansible-playbook -i inventory.ini tagged-nginx-playbook.yml --skip-tags restart

# List Available Tags
ansible-playbook tagged-nginx-playbook.yml --list-tags

πŸ’‘ Sample Output:

playbook: tagged-nginx-playbook.yml
  play #1 (all): Categorized Nginx Deployment TAGS: [all, config, install, restart]

πŸ”Ή Challenge 6: Refactor a playbook using include_tasks or import_tasks

πŸ“ Final Folder Structure

.
β”œβ”€β”€ inventory.ini
β”œβ”€β”€ site.yml
β”œβ”€β”€ tasks/
β”‚   β”œβ”€β”€ install.yml
β”‚   β”œβ”€β”€ config.yml
β”‚   └── restart.yml
└── files/
    └── index.html

inventory.ini

[web]
localhost ansible_connection=local

tasks/install.yml

- name: Install Nginx
  package:
    name: nginx
    state: present
  tags: install

tasks/config.yml

- name: Copy index.html
  copy:
    src: files/index.html
    dest: /var/www/html/index.html   # Ubuntu/Debian web root (RHEL: /usr/share/nginx/html)
    mode: '0644'
  notify: Restart Nginx
  tags: config

tasks/restart.yml

- name: Ensure Nginx is running and enabled
  service:
    name: nginx
    state: started
    enabled: yes
  tags: restart

site.yml (Main Playbook)

---
- name: Nginx Deployment (Refactored)
  hosts: web
  become: yes
  tasks:
    - import_tasks: tasks/install.yml
    - import_tasks: tasks/config.yml
    - import_tasks: tasks/restart.yml

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

πŸ’‘ Pro Tip:
Use include_tasks for dynamic task loading with when: conditions.

---
- name: Include tasks dynamically based on OS
  hosts: all
  become: yes
  tasks:
    - name: Include Ubuntu-specific tasks
      include_tasks: tasks/install_ubuntu.yml
      when: ansible_os_family == "Debian"

    - name: Include RedHat/Amazon tasks
      include_tasks: tasks/install_rhel.yml
      when: ansible_os_family in ["RedHat", "Amazon"]

    - name: Include MacOS tasks
      include_tasks: tasks/install_macos.yml
      when: ansible_os_family == "Darwin"


πŸ”Ή Challenge 7: Create a main.yml file and use vars_files to separate the configuration

πŸ“ Structure

.
β”œβ”€β”€ inventory.ini
β”œβ”€β”€ main.yml
β”œβ”€β”€ vars.yml
└── files/
    └── index.html

vars.yml

web_package: nginx
web_service: nginx
html_src: files/index.html
html_dest: /var/www/html/index.html   # Ubuntu/Debian web root (RHEL: /usr/share/nginx/html)

main.yml

---
- name: Install and configure web server using external vars
  hosts: all
  become: yes
  vars_files:
    - vars.yml
  tasks:
    - name: Install web package
      package:
        name: "{{ web_package }}"
        state: present
      tags: install

    - name: Copy custom index.html
      copy:
        src: "{{ html_src }}"
        dest: "{{ html_dest }}"
        mode: '0644'
      notify: Restart web service
      tags: config

    - name: Ensure web service is started and enabled
      service:
        name: "{{ web_service }}"
        state: started
        enabled: yes
      tags: restart

  handlers:
    - name: Restart web service
      service:
        name: "{{ web_service }}"
        state: restarted

πŸ”Ή Challenge 8: Set up a playbook that creates a user, installs a package, and starts a service β€” all in one run

full-setup.yml

---
- name: Full system setup: user + package + service
  hosts: all
  become: yes
  vars:
    username: devopsuser
    web_package: nginx
    web_service: nginx

  tasks:
    - name: Create system user
      ansible.builtin.user:
        name: "{{ username }}"
        shell: /bin/bash
        create_home: yes
        system: yes

    - name: Install web package (e.g., Nginx)
      ansible.builtin.package:
        name: "{{ web_package }}"
        state: present

    - name: Ensure service is running and enabled
      ansible.builtin.service:
        name: "{{ web_service }}"
        state: started
        enabled: yes

πŸ”Ή Challenge 9: Add a rescue block to handle command failure gracefully

rescue-example.yml

---
- name: Handle command failure with rescue block
  hosts: all
  become: yes

  tasks:
    - name: Try block to run a command that may fail
      block:
        - name: Run a risky command
          command: /bin/false  # Simulates failure
          register: result
          ignore_errors: no

      rescue:
        - name: Handle failure gracefully
          debug:
            msg: "❌ The command failed. Executing rescue tasks..."

      always:
        - name: Always run this step
          debug:
            msg: "βœ… Cleanup or final steps executed no matter what."


πŸ”Ή Challenge 10: Create a reusable playbook role structure manually (without ansible-galaxy)

πŸ“ Folder Structure

.
β”œβ”€β”€ inventory.ini
β”œβ”€β”€ site.yml
β”œβ”€β”€ roles/
β”‚   └── webserver/
β”‚       β”œβ”€β”€ tasks/
β”‚       β”‚   └── main.yml
β”‚       β”œβ”€β”€ handlers/
β”‚       β”‚   └── main.yml
β”‚       β”œβ”€β”€ files/
β”‚       β”‚   └── index.html
β”‚       └── vars/
β”‚           └── main.yml

site.yml

---
- name: Apply webserver role
  hosts: web
  become: yes
  roles:
    - webserver

inventory.ini

[web]
localhost ansible_connection=local

roles/webserver/vars/main.yml

web_package: nginx
web_service: nginx
web_root: /var/www/html/index.html   # RHEL: /usr/share/nginx/html/index.html

roles/webserver/files/index.html

<!DOCTYPE html>
<html>
<body>
<h1>πŸš€ Deployed via Ansible Role!</h1>
</body>
</html>

roles/webserver/tasks/main.yml

---
- name: Install web package
  package:
    name: "{{ web_package }}"
    state: present

- name: Copy index.html
  copy:
    src: index.html
    dest: "{{ web_root }}"
    mode: '0644'
  notify: Restart web service

- name: Ensure service is started and enabled
  service:
    name: "{{ web_service }}"
    state: started
    enabled: yes

roles/webserver/handlers/main.yml

---
- name: Restart web service
  service:
    name: "{{ web_service }}"
    state: restarted

▢️ Run the Role

ansible-playbook -i inventory.ini site.yml

πŸ”Ή Challenge 11: Set up a cron job using Ansible to schedule a periodic backup script

πŸ“ Folder Structure

.
β”œβ”€β”€ inventory.ini
β”œβ”€β”€ backup-playbook.yml
└── files/
    └── backup.sh

files/backup.sh

#!/bin/bash
# Backup script: archives /data to /backup
timestamp=$(date +%F-%H%M)
mkdir -p /backup
tar -czf /backup/data-backup-$timestamp.tar.gz /data 2>/dev/null

backup-playbook.yml

---
- name: Setup backup script and cron job
  hosts: backup
  become: yes
  tasks:
    - name: Copy backup script
      copy:
        src: files/backup.sh
        dest: /usr/local/bin/backup.sh
        mode: '0755'
        owner: root
        group: root

    - name: Schedule cron job to run daily at 2 AM
      cron:
        name: "Daily data backup"
        user: root
        job: "/usr/local/bin/backup.sh"
        minute: "0"
        hour: "2"
        state: present

▢️ Run the Playbook

ansible-playbook -i inventory.ini backup-playbook.yml

βœ… Check Cron

sudo crontab -l
# Expected line: 0 2 * * * /usr/local/bin/backup.sh

πŸ”Ή Challenge 12: Write a playbook to deploy a web app with Git clone, package install, config setup, and service start

πŸ“ Folder Structure

.
β”œβ”€β”€ inventory.ini
β”œβ”€β”€ deploy-app.yml
β”œβ”€β”€ vars.yml
└── files/
    └── config.env

vars.yml

app_repo: "https://github.com/example/my-flask-app.git"
app_dest: "/opt/myapp"
app_packages:
  - python3
  - python3-pip
  - python3-venv
  - git
gunicorn_port: 8000

files/config.env

APP_ENV=production
APP_DEBUG=False

deploy-app.yml

---
- name: Deploy web app from Git
  hosts: web
  become: yes
  vars_files:
    - vars.yml

  tasks:
    - name: Install required packages
      package:
        name: "{{ app_packages }}"
        state: present

    - name: Clone the web app repository
      git:
        repo: "{{ app_repo }}"
        dest: "{{ app_dest }}"
        version: main
        force: yes

    - name: Copy environment config
      copy:
        src: files/config.env
        dest: "{{ app_dest }}/.env"
        mode: '0644'

    - name: Install Python dependencies
      pip:
        requirements: "{{ app_dest }}/requirements.txt"
        virtualenv: "{{ app_dest }}/venv"
        virtualenv_command: python3 -m venv   # no separate virtualenv tool needed

    - name: Create systemd service for gunicorn
      copy:
        dest: /etc/systemd/system/myapp.service
        content: |
          [Unit]
          Description=Gunicorn instance to serve myapp
          After=network.target

          [Service]
          User=root
          Group=www-data
          WorkingDirectory={{ app_dest }}
          EnvironmentFile={{ app_dest }}/.env
          ExecStart={{ app_dest }}/venv/bin/gunicorn -b 0.0.0.0:{{ gunicorn_port }} app:app

          [Install]
          WantedBy=multi-user.target
      notify: Restart web service

    - name: Enable and start app service
      systemd:
        name: myapp
        daemon_reload: yes   # pick up the new unit file
        enabled: yes
        state: started

  handlers:
    - name: Restart web service
      systemd:
        name: myapp
        daemon_reload: yes
        state: restarted

▢️ Run the Playbook

ansible-playbook -i inventory.ini deploy-app.yml

πŸ”Ή Challenge 13: Configure firewall rules using Ansible (UFW/Firewalld)

firewall-setup.yml

---
- name: Configure firewall rules based on OS
  hosts: all
  become: yes
  tasks:
    # Ubuntu/Debian - UFW
    - name: Install UFW
      apt:
        name: ufw
        state: present
        update_cache: yes
      when: ansible_os_family == 'Debian'

    - name: Allow SSH, HTTP, HTTPS on UFW
      ufw:
        rule: allow
        port: "{{ item }}"
      loop: [22, 80, 443]
      when: ansible_os_family == 'Debian'

    - name: Enable UFW
      ufw:
        state: enabled
        policy: deny   # block all other inbound traffic by default
      when: ansible_os_family == 'Debian'

    # CentOS/RHEL - firewalld
    - name: Ensure firewalld is installed
      package:
        name: firewalld
        state: present
      when: ansible_os_family == 'RedHat'

    - name: Start and enable firewalld
      service:
        name: firewalld
        state: started
        enabled: yes
      when: ansible_os_family == 'RedHat'

    - name: Open ports in firewalld
      firewalld:
        port: "{{ item }}/tcp"
        permanent: yes
        state: enabled
        immediate: yes
      loop: [22, 80, 443]
      when: ansible_os_family == 'RedHat'

▢️ Run:

ansible-playbook -i inventory.ini firewall-setup.yml

πŸ”Ή Challenge 14: Automate SSL certificate generation using Let’s Encrypt

ssl-deploy.yml

---
- name: Automate Let's Encrypt SSL with Nginx
  hosts: web
  become: yes
  vars:
    domain: yourdomain.com
    email: [email protected]
  tasks:
    - name: Install packages
      apt:
        name:
          - nginx
          - python3-certbot-nginx
        state: present
        update_cache: yes
      when: ansible_os_family == "Debian"

    - name: Ensure Nginx is running
      service:
        name: nginx
        state: started
        enabled: yes

    - name: Add Nginx config
      copy:
        dest: "/etc/nginx/sites-available/{{ domain }}"
        content: |
          server {
            listen 80;
            server_name {{ domain }};
            root /var/www/html;
            index index.html index.htm;
            location / {
              try_files $uri $uri/ =404;
            }
          }
      notify: Reload Nginx

    - name: Symlink Nginx site
      file:
        src: "/etc/nginx/sites-available/{{ domain }}"
        dest: "/etc/nginx/sites-enabled/{{ domain }}"
        state: link
        force: yes

    - name: Generate SSL cert
      command: >
        certbot --nginx -d {{ domain }} --non-interactive --agree-tos --email {{ email }} --redirect
      args:
        creates: "/etc/letsencrypt/live/{{ domain }}/fullchain.pem"
      notify: Reload Nginx

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

▢️ Run:

ansible-playbook -i inventory.ini ssl-deploy.yml

πŸ”Ή Challenge 15: Use Jinja2 template to deploy config

template-config.yml

---
- name: Deploy Nginx config using Jinja2
  hosts: web
  become: yes
  vars_files:
    - vars.yml
  tasks:
    - name: Create web root
      file:
        path: "{{ web_root }}"
        state: directory
        owner: www-data
        group: www-data
        mode: '0755'

    - name: Deploy templated config
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/sites-available/{{ domain }}
        mode: '0644'
      notify: Reload Nginx

    - name: Enable site
      file:
        src: /etc/nginx/sites-available/{{ domain }}
        dest: /etc/nginx/sites-enabled/{{ domain }}
        state: link
        force: yes

    - name: Ensure Nginx running
      service:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

vars.yml

domain: example.com
web_root: /var/www/example.com

templates/nginx.conf.j2

server {
    listen 80;
    server_name {{ domain }};
    root {{ web_root }};
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

πŸ”Ή Challenge 16: Deploy multi-node app with DB β†’ App β†’ LB

deploy.yml

---
- name: Setup DB
  hosts: db
  become: yes
  roles:
    - db

- name: Deploy App
  hosts: app
  become: yes
  roles:
    - app

- name: Configure LB
  hosts: lb
  become: yes
  roles:
    - lb

Example: roles/db/tasks/main.yml

- name: Install MySQL
  apt:
    name: "{{ db_engine | default('mysql-server') }}"
    state: present
    update_cache: yes

- name: Start MySQL
  service:
    name: mysql
    state: started
    enabled: yes

Example: roles/app/tasks/main.yml (keep db_password in an Ansible Vault file, see Day 23)

- name: Install deps
  apt:
    name:
      - git
      - python3
      - python3-pip
    state: present

- name: Clone app
  git:
    repo: "{{ app_repo }}"
    dest: "{{ app_dest }}"
    force: yes

- name: Configure DB
  copy:
    dest: "{{ app_dest }}/.env"
    content: |
      DB_HOST={{ db_host }}
      DB_USER=myappuser
      DB_PASS={{ db_password }}
      DB_NAME=myapp

- name: Install Python deps
  pip:
    requirements: "{{ app_dest }}/requirements.txt"

Example: roles/lb/templates/lb.conf.j2

{# backend_servers comes from group_vars/lb.yml, e.g. {{ groups['app'] }} #}
upstream app_servers {
  {% for server in backend_servers %}
  server {{ server }}:5000;
  {% endfor %}
}

server {
  listen 80;
  location / {
    proxy_pass http://app_servers;
  }
}

▢️ Run:

ansible-playbook -i inventory.ini deploy.yml

πŸ”Ή Challenge 17: Create an Ansible role that can be reused across projects ("common" role)

πŸ“ Directory Structure

.
β”œβ”€β”€ inventory.ini
β”œβ”€β”€ site.yml
└── roles/
    └── common/
        β”œβ”€β”€ tasks/
        β”‚   └── main.yml
        β”œβ”€β”€ vars/
        β”‚   └── main.yml
        β”œβ”€β”€ handlers/
        β”‚   └── main.yml
        └── templates/
            └── motd.j2

inventory.ini

[servers]
your.host.ip ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa

site.yml

---
- name: Apply common configuration to all hosts
  hosts: all
  become: yes
  roles:
    - common

roles/common/vars/main.yml

common_packages:
  - vim
  - curl
  - git
timezone: UTC
motd_message: "Welcome to {{ inventory_hostname }} - Managed by Ansible"

roles/common/tasks/main.yml

---
- name: Update apt cache
  apt:
    update_cache: yes
  when: ansible_os_family == 'Debian'

- name: Install common packages
  package:
    name: "{{ common_packages }}"
    state: present

- name: Set timezone
  community.general.timezone:
    name: "{{ timezone }}"

- name: Set custom MOTD
  template:
    src: motd.j2
    dest: /etc/motd
    owner: root
    group: root
    mode: '0644'

- name: Create default system user
  user:
    name: ansible
    comment: "Managed by Ansible"
    shell: /bin/bash
    create_home: yes
    system: yes

- name: Allow 'ansible' user passwordless sudo
  copy:
    dest: /etc/sudoers.d/ansible
    content: "ansible ALL=(ALL) NOPASSWD:ALL\n"
    mode: '0440'
    validate: /usr/sbin/visudo -cf %s   # a broken sudoers file locks you out

roles/common/templates/motd.j2

{{ motd_message }}

▢️ Run It

ansible-playbook -i inventory.ini site.yml

🀷🏻 How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das), and use #60DaysOfDevOps to engage with the community!



⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post