DevOps
Infrastructure as Code
Ansible Practical: Installation & First Playbook

Ansible Practical: Installation & First Playbook

Go from a fresh server to a fully automated control node. This guide will walk you through setting up Ansible on an Ubuntu 24.04 instance in AWS and running your first configuration playbook.


🛠️ Step 1: Environment Setup

  1. Launch an AWS EC2 Instance using:
    • AMI: Ubuntu 24.04 LTS
    • Instance Type: t3.micro (or t2.micro)
    • Key Pair: your-key.pem
  2. Connect to your instance via SSH:
    ssh -i "your-key.pem" ubuntu@your-public-ip

📦 Step 2: Installing Ansible

Run the following commands to install the latest stable version of Ansible.

  1. Update package lists:

    sudo apt update
  2. Add the official Ansible PPA:

    sudo apt install software-properties-common
    sudo add-apt-repository --yes --update ppa:ansible/ansible
  3. Install Ansible:

    sudo apt install ansible -y
  4. Verify the installation:

    ansible --version

    You should see output indicating Ansible 2.16+ is installed.


🧪 Step 3: Your First Playbook Laboratory

Let's create a dedicated folder to test our automation.

mkdir ansible-lab && cd ansible-lab

1. Define the Inventory

Create a file named hosts and add the following content. This tells Ansible to target the local machine (the control node itself) for this test.

[webservers]
localhost ansible_connection=local

2. Write the Playbook

Create a file named install-nginx.yml with this YAML content:

---
- name: Hello Ansible - Install Nginx
  hosts: webservers
  become: yes  # Runs tasks as root/sudo
  
  tasks:
    - name: Ensure Nginx is installed
      apt:
        name: nginx
        state: latest
        
    - name: Ensure Nginx is started
      service:
        name: nginx
        state: started

🚀 Step 4: The Execution

Run the playbook using the ansible-playbook command:

ansible-playbook -i hosts install-nginx.yml

Understanding the Output:

  • ok=2: Tasks that were already in the correct state (Idempotency).
  • changed=2: Tasks where Ansible actually performed an action (e.g., installed the package).
  • failed=0: Everything went smoothly!

[!IMPORTANT] Why use the PPA? The default Ubuntu repositories often lag behind. Adding the official ppa:ansible/ansible ensures you have access to the latest modules and security features without waiting for the next OS release cycle.