Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 29 ยท Projects

Project: Provision a Web Server

Build a complete Ansible playbook that installs nginx, renders a site config from a template, opens the firewall, reloads safely with handlers and verifies the result.

In this project you will write one playbook that turns a blank Ubuntu or Debian server into a working web server: nginx installed, a site configuration generated from a template, a firewall that allows only SSH and web traffic, a handler that validates and reloads nginx only when something changed, and a final check that the site really answers. It brings together inventory, variables, modules, templates and handlers from the earlier lessons.

You need a lab machine you can SSH into (a virtual machine or a container that runs systemd and SSH, see Installing Ansible and Your First Ping). Never test a firewall playbook on a server you cannot reach another way: a wrong rule can lock you out.

Ansible and nginx cannot run on this site, so the inventory and the playbook below are read-only. The runnable parts are Node.js stand-ins hosted on the site's server runner: one renders the nginx template the way the template module would, and one shows why the config task reports changed only once. They model the behaviour; they are not Ansible.

The plan

flowchart TD
  A["Install nginx<br/>(package)"] --> B["Create web root<br/>and index page"]
  B --> C["Render site config<br/>(template)"]
  C --> D["Enable site,<br/>disable default"]
  D --> E["Firewall rules<br/>(ufw)"]
  E --> F["Flush handlers:<br/>validate then reload"]
  F --> G["Start and enable nginx"]
  G --> H["Verify with uri"]

Every box is one or two tasks; the handler runs only when the template or the site links changed.

Project layout

Keep the project small and conventional so it is easy to grow into a role later (see Roles and Project Layout).

TEXT
webserver/
  ansible.cfg
  inventory.ini
  site.yml
  templates/
    site.conf.j2
INI
# inventory.ini
[web]
web1 ansible_host=192.0.2.10

[web:vars]
ansible_user=deploy

The address above is from a documentation range; use your lab machine's address. The deploy user needs SSH key access and sudo, as explained in SSH, Privilege Escalation and Hardening.

The site template

The template holds the nginx server block, with the parts that change as variables. A for loop adds a security header per list entry, so adding a header never means editing the structure.

JINJA
server {
    listen {{ listen_port }};
    server_name {{ server_name }};
    root {{ web_root }};
    index index.html;
{% for header in security_headers %}
    add_header {{ header.name }} "{{ header.value }}" always;
{% endfor %}

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

Stand-in: render the template

This Node.js program implements just enough of Jinja2 (variable lookup with dots and one kind of for loop) to render the template above. Like Ansible's default, it removes the newline after a {% ... %} tag. Real Jinja2 does much more (see Jinja2 Templates and Filters); this shows the principle.

Node.js Render the nginx site template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last lines show the useful failure mode: a missing variable stops the run with a clear message instead of writing a broken file. Real Ansible behaves the same way by default and reports an undefined variable.

The playbook

YAML
# site.yml
- name: Provision a web server
  hosts: web
  become: true
  vars:
    server_name: shop.example.com
    listen_port: 80
    web_root: /var/www/shop
    security_headers:
      - { name: X-Content-Type-Options, value: nosniff }
      - { name: X-Frame-Options, value: SAMEORIGIN }

  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Create the web root
      ansible.builtin.file:
        path: "{{ web_root }}"
        state: directory
        owner: www-data
        group: www-data
        mode: "0755"

    - name: Publish a first page
      ansible.builtin.copy:
        dest: "{{ web_root }}/index.html"
        content: "<h1>{{ server_name }} is up</h1>\n"
        owner: www-data
        group: www-data
        mode: "0644"

    - name: Render the site configuration
      ansible.builtin.template:
        src: site.conf.j2
        dest: "/etc/nginx/sites-available/{{ server_name }}.conf"
        owner: root
        group: root
        mode: "0644"
      notify: reload nginx

    - name: Enable the site
      ansible.builtin.file:
        src: "/etc/nginx/sites-available/{{ server_name }}.conf"
        dest: "/etc/nginx/sites-enabled/{{ server_name }}.conf"
        state: link
      notify: reload nginx

    - name: Disable the default site
      ansible.builtin.file:
        path: /etc/nginx/sites-enabled/default
        state: absent
      notify: reload nginx

    - name: Allow SSH before enabling the firewall
      community.general.ufw:
        rule: allow
        port: "22"
        proto: tcp

    - name: Allow web traffic
      community.general.ufw:
        rule: allow
        port: "{{ listen_port }}"
        proto: tcp

    - name: Turn the firewall on
      community.general.ufw:
        state: enabled
        policy: deny
        direction: incoming

    - name: Apply pending nginx changes now
      ansible.builtin.meta: flush_handlers

    - name: Make sure nginx runs and starts at boot
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

    - name: Verify the site answers
      ansible.builtin.uri:
        url: "http://127.0.0.1:{{ listen_port }}/"
        status_code: 200
        return_content: true
      register: site
      failed_when: "'is up' not in site.content"
      changed_when: false

  handlers:
    - name: Validate nginx configuration
      ansible.builtin.command: nginx -t
      changed_when: false
      listen: reload nginx

    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded
      listen: reload nginx

Several choices are worth explaining.

  • The SSH rule comes first. The firewall is switched on only after port 22 is allowed, so your own connection survives. This order is the single most important line in the playbook.
  • Handlers share a listen topic. Both handlers react to reload nginx and run in the order they are defined, so the configuration is tested with nginx -t before nginx reloads. If the test fails, the reload never happens and the old working configuration keeps serving. (A site file cannot be validated with the template module's validate option, because it is only a fragment of the full configuration; nginx -t checks the whole thing.)
  • flush_handlers runs the handlers now, before the service task and the verification, instead of at the very end of the play.
  • failed_when on the check makes the play fail loudly if the page does not contain the expected text, and changed_when: false stops a read-only check from reporting a change.
  • File modes are strings such as "0644", so YAML cannot misread them as numbers.

Stand-in: why the config task changes only once

The template module renders the file on the control node and compares it with the file on the host; only a difference counts as a change and triggers the handler. This model uses a checksum comparison against a fake file system to show the three outcomes: first run, repeat run and a changed variable.

Node.js Template task: changed once, ok afterwards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Running and checking the project

Terminal
ansible-playbook -i inventory.ini site.yml --syntax-check
ansible-playbook -i inventory.ini site.yml --check --diff
ansible-playbook -i inventory.ini site.yml
ansible-playbook -i inventory.ini site.yml     # second run: expect changed=0

Check mode on a fresh machine can fail at tasks that depend on earlier ones (nginx is not installed yet, so its directories do not exist); that is normal for a first run. The important test is the last command: a second run should report changed=0. Any task that changes again is not idempotent and needs fixing (see Modules and Idempotence).

HTTPS: what to add next

This project serves plain HTTP so that every step can be checked from the machine itself. A real site needs TLS. The usual next steps are:

  • Obtain a certificate (for example with Let's Encrypt and certbot, or the community.crypto collection's ACME modules) and add a second server block listening on 443 with ssl_certificate and ssl_certificate_key.
  • Open port 443 in the firewall, and redirect port 80 to HTTPS.
  • Store private keys with strict modes (0600, owned by root) and never commit them unencrypted; see Ansible Vault and Secrets.
  • Add a task that renews certificates and a handler that reloads nginx afterwards.

Validate the finished setup from outside the server, and be careful with automated issuance during testing, because certificate authorities limit how often you may request certificates.

Extend the project

  • Turn the playbook into a role with defaults/main.yml for the variables.
  • Support several sites by looping over a sites list in the template task.
  • Add a tags: entry per stage so you can run only --tags config.
  • Run it against two hosts with serial: 1 and see the next project, Deploy an Application with Rolling Updates.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the playbook allow port 22 before enabling the firewall?

    With a deny-incoming policy, a missing SSH rule locks you out mid-run. Allowing SSH first keeps the connection alive.
  2. 2. What makes the 'Render the site configuration' task report ok on the second run?

    The template module renders the file and compares it with the destination. Identical content means no change and therefore no notification.
  3. 3. Two handlers listen to reload nginx. In what order do they run?

    Handlers run in definition order, so putting nginx -t before the reload means a bad configuration never gets reloaded.
  4. 4. What does meta: flush_handlers do?

    Normally handlers run at the end of the play. flush_handlers runs the pending ones at that point, so later tasks (like the verification) see the new configuration.

Summary

  • A web server build is a short chain: package, directory and page, templated config, enabled site, firewall, handler, service, verification.
  • Put SSH in the firewall rules before turning the firewall on, and keep file modes as strings.
  • Handlers sharing a listen topic run in definition order, so validate with nginx -t before reloading; flush_handlers applies them early.
  • The template module changes a file only when the rendered text differs, which makes the second run report changed=0.
  • Verify with uri, use changed_when: false on read-only checks, and plan TLS as the next step.

Next: Project: Deploy an Application with Rolling Updates.