DevOps Engineering Operate and automate hosts19 / 21

SECTION 05 · 40 MIN READ & EXPLORE

Describe the host with Ansible

Use inventory, modules, handlers, and repeatable playbooks to configure the same application.

Ansible is Agentless (needs no software on the target) and Push-based (you send commands from your laptop/control node).

Concept Definition
Control Node The machine where you run the ansible commands (e.g., your laptop).
Managed Node The destination server you are configuring (e.g., 10.70.81.68).
Inventory A file (usually hosts.ini) listing all your managed nodes.
Playbook The YAML file defining the “state” you want (the automation script).
Module The tools Ansible uses to do the work (e.g., apt, copy, service).
Task A single action using a module (e.g., “Install Nginx”).
Idempotency The principle that running the same playbook twice shouldn’t break anything.

2. The Command Line (CLI)

Command Usage
ansible-playbook Run a playbook.

ansible-playbook -i hosts.ini deploy.yml | | ansible | Run an ad-hoc command. (One-off task without a file)

ansible all -i hosts.ini -m ping | | ansible-galaxy | Download roles.

ansible-galaxy install geerlingguy.nginx | | ansible-vault | Manage secrets.

ansible-vault encrypt secrets.yml | | --syntax-check | Debug. Checks if your YAML is valid.

ansible-playbook deploy.yml --syntax-check | | --step | Interactive mode. Asks for confirmation before every task. |


3. Inventory (hosts.ini)

This is the “Address Book” for your servers.

# Grouping servers
[webservers]
10.70.81.68

[dbservers]
db01.example.com

# Group of Groups
[production:children]
webservers
dbservers

# Setting connection variables inline
[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_rsa

4. Playbook Anatomy (deploy.yml)

A Playbook maps a Group of hosts to a list of Tasks.

---
- name: Configure Web Server  # Name of the 'Play'
  hosts: webservers           # Target from inventory
  become: yes                 # Run as sudo (root)

  vars:                       # Define variables
    http_port: 80

  tasks:                      # The list of actions
    - name: Ensure Nginx is installed
      apt:                    # The Module name
        name: nginx
        state: present        # The desired state

    - name: Copy Config File
      copy:
        src: ./nginx.conf
        dest: /etc/nginx/nginx.conf
      notify: Restart Nginx   # Triggers a handler if changed

  handlers:                   # Only runs if 'notify' is triggered
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

5. Essential Modules

You will use these for almost every project.

Module Purpose Example
**apt / yum** Manage packages. name: nginx state: present
copy Upload a file. src: local.txt dest: /remote/path
file Manage permissions/dirs. path: /opt/app state: directory mode: '0755'
template Upload file + inject vars. src: config.j2 dest: /etc/config
service Manage Systemd. name: docker state: started enabled: yes
user Create users. name: deploy_user shell: /bin/bash
git Clone repos. repo: https://github.com/... dest: /app
lineinfile Edit a single line in a file. Add a line to .bashrc
shell Run raw terminal commands. Use sparingly! (Not idempotent)
debug Print variables. msg: "The IP is {{ ansible_default_ipv4.address }}"

6. Variables & Facts

  • Facts (ansible_facts): Information Ansible automatically gathers about the target (OS, IP, CPU, RAM).

  • Example: {{ ansible_distribution }} might output “Ubuntu”.

  • Variables: Defined by you (in playbooks, inventory, or group_vars).

  • Usage: dest: "/var/www/{{ domain_name }}"

7. Conditionals & Loops

When (If Statement):

- name: Install Apache
  apt:
    name: apache2
    state: present
  when: ansible_os_family == "Debian"  # Only runs on Debian/Ubuntu

Loop (For Loop):

- name: Create multiple users
  user:
    name: "{{ item }}"
    state: present
  loop:
    - alice
    - bob
    - charlie
HANDS-ON LAB

Rebuild the host declaratively

Configure your own disposable VM, run the playbook twice, and compare the reported changes.

Your mission

  • Configure your own disposable VM, run the playbook twice, and compare the reported changes.

Download and extract the archive. Work inside 09-sysadmin; upload its contents to the root of a GitLab project when a pipeline is involved.

Replace the documentation-only address in hosts.ini. Use a key you generated yourself; no course private key is supplied.

ansible all -i hosts.ini -m ping
ansible-playbook -i hosts.ini sysadmin-lab.yml --syntax-check
ansible-playbook -i hosts.ini sysadmin-lab.yml
ansible-playbook -i hosts.ini sysadmin-lab.yml

Compare changed counts and verify curl http://localhost:3000 on the VM. The playbook flushes handlers and ensures the application is started before checking its port.

How to know it worked

  • The playbook verifies port 3000 after starting the app.
  • The second run makes fewer changes and the application still responds.
Download lesson files

Explore the files

hosts.ini

[webservers]
# Replace with your disposable Ubuntu VM address.
lab ansible_host=192.0.2.10 ansible_user=ubuntu

sysadmin-lab.yml

---
- name: SysAdmin Lab - Complete Automation
  hosts: webservers
  become: yes  # This runs everything with 'sudo'
  vars:
    app_dir: /opt/node-app

  tasks:
    # --- CHAPTER 1: Provisioning (Nginx & Node) ---
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Install required packages
      apt:
        name:
          - nginx
          - nodejs
          - curl
        state: present

    - name: Create application directory
      file:
        path: "{{ app_dir }}"
        state: directory
        mode: '0755'

    - name: Deploy Node.js Application Code (server.js)
      copy:
        dest: "{{ app_dir }}/server.js"
        content: |
          const http = require('http');
          const fs = require('fs');
          const path = require('path');
          const LOG_FILE = path.join(__dirname, 'access.log');
          const PORT = 3000;

          const server = http.createServer((req, res) => {
              const logEntry = `${new Date().toISOString()} - Request from ${req.socket.remoteAddress}\n`;
              fs.appendFile(LOG_FILE, logEntry, (err) => {
                  if (err) console.error('Error writing log:', err);
              });
              res.statusCode = 200;
              res.setHeader('Content-Type', 'text/plain');
              res.end('Hello from Ansible managed server!\n');
          });

          server.listen(PORT, () => {
              console.log(`Server running on port ${PORT}`);
          });

    # --- CHAPTER 2: Service Management (Systemd) ---
    - name: Create Systemd Service for Node App
      copy:
        dest: /etc/systemd/system/node-app.service
        content: |
          [Unit]
          Description=Node App Managed by Ansible
          After=network.target

          [Service]
          ExecStart=/usr/bin/node {{ app_dir }}/server.js
          Restart=always
          RestartSec=5
          WorkingDirectory={{ app_dir }}
          StandardOutput=syslog
          SyslogIdentifier=node-app

          [Install]
          WantedBy=multi-user.target
      notify: Restart Node App

    # --- CHAPTER 3: Timers & Cron (Log Cleaner) ---
    - name: Deploy Log Cleanup Script
      copy:
        dest: "{{ app_dir }}/cleanup.sh"
        mode: '0755' # Make it executable
        content: |
          #!/bin/bash
          LOG_FILE="{{ app_dir }}/access.log"
          MAX_SIZE=10240 
          if [ -f "$LOG_FILE" ]; then
              FILE_SIZE=$(stat -c%s "$LOG_FILE")
              if [ $FILE_SIZE -gt $MAX_SIZE ]; then
                  echo "$(date): Cleaning log file..."
                  rm "$LOG_FILE"
              fi
          fi

    - name: Create Systemd Service for Cleaner (OneShot)
      copy:
        dest: /etc/systemd/system/log-cleaner.service
        content: |
          [Unit]
          Description=Run Log Cleanup Script

          [Service]
          Type=oneshot
          ExecStart={{ app_dir }}/cleanup.sh

    - name: Create Systemd Timer for Cleaner
      copy:
        dest: /etc/systemd/system/log-cleaner.timer
        content: |
          [Unit]
          Description=Run Log Cleaner every minute

          [Timer]
          OnBootSec=1min
          OnUnitActiveSec=1min

          [Install]
          WantedBy=timers.target

    - name: Enable and Start Timer
      systemd:
        name: log-cleaner.timer
        state: started
        enabled: yes
        daemon_reload: yes

    - name: Apply pending service changes before verification
      meta: flush_handlers

    - name: Ensure application is enabled and running
      systemd:
        name: node-app
        state: started
        enabled: yes
        daemon_reload: yes

    # --- CHAPTER 4: Verification ---
    - name: Verify App is Running (Check Port 3000)
      wait_for:
        port: 3000
        delay: 2
        timeout: 30

  handlers:
    # This only runs if the "Create Systemd Service" task changes something
    - name: Restart Node App
      systemd:
        name: node-app
        state: restarted
        enabled: yes
        daemon_reload: yes

user-data.yaml

#cloud-config
package_update: true
packages:
  - openssh-server
  - curl
  - git

users:
  - name: ubuntu
    shell: /bin/bash
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
    ssh_authorized_keys:
      - ssh-ed25519 REPLACE_WITH_YOUR_PUBLIC_KEY
A LITTLE CLEARER?

Take a moment to explain the idea in your own words.

Progress is saved in this browser.

DevOps Engineering

Course overview ↗

01Introduction to DevOps

  1. What is DevOps?20m
  2. DevOps Roles20m