Console9

Ansible tutorial: automate server setup from scratch

Learn Ansible by automating a complete Ubuntu server setup — users, packages, firewall, and services.

Ansible tutorial: automate server setup from scratch

Learn Ansible by automating a complete Ubuntu server setup — users, packages, firewall, and services.

What You Will Need

  • An Ubuntu 22.04+ server with SSH access.
  • Ansible installed on your local machine (the control node).

Step 1: Create an Ansible Inventory File

Ansible needs to know which servers to manage. Create inventory.ini with the server's IP address:

[webservers]
203.0.113.10 ansible_user=root

The ansible_user variable tells Ansible which SSH user to connect as.

Step 2: Test Connectivity with an Ansible Ad-Hoc Command

Ansible verifies SSH connectivity with the ping module (this is an Ansible ping, not ICMP):

ansible -i inventory.ini webservers -m ping

A successful response shows "pong" from each host.

Step 3: Write a Playbook to Install Packages with Ansible

Ansible playbooks define the desired state of the server in YAML. Create site.yml:

---
- name: Set up web server
  hosts: webservers
  become: true
  tasks:
    - name: Update apt cache
      apt:
        update_cache: true
        cache_valid_time: 3600

    - name: Install required packages
      apt:
        name:
          - nginx
          - ufw
          - fail2ban
        state: present

The become: true directive runs tasks with sudo privileges. The apt module ensures packages are installed.

Step 4: Add Firewall and Service Tasks to the Ansible Playbook

Extend the playbook to configure UFW and start services:

    - name: Allow SSH through UFW
      ufw:
        rule: allow
        port: '22'
        proto: tcp

    - name: Allow HTTP through UFW
      ufw:
        rule: allow
        port: '80'
        proto: tcp

    - name: Enable UFW
      ufw:
        state: enabled

    - name: Start and enable Nginx
      service:
        name: nginx
        state: started
        enabled: true

Step 5: Run the Ansible Playbook

Execute the playbook against the inventory:

ansible-playbook -i inventory.ini site.yml

Ansible reports the status of each task: ok (already correct), changed (action taken), or failed (error).

What You Learned

This tutorial covered Ansible inventory files (defining managed hosts), ad-hoc commands (testing connectivity), playbook structure (plays, tasks, modules), privilege escalation ( become: true), and the apt, ufw, and service modules. Run the same playbook again — Ansible reports ok for every task, demonstrating idempotency.