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
- Launch an AWS EC2 Instance using:
- AMI: Ubuntu 24.04 LTS
- Instance Type: t3.micro (or t2.micro)
- Key Pair: your-key.pem
- 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.
-
Update package lists:
sudo apt update -
Add the official Ansible PPA:
sudo apt install software-properties-common sudo add-apt-repository --yes --update ppa:ansible/ansible -
Install Ansible:
sudo apt install ansible -y -
Verify the installation:
ansible --versionYou 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-lab1. 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=local2. 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.ymlUnderstanding 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.