What is Ansible?
Ansible automates server configuration, application deployment, and task orchestration. It connects via SSH — no agent needed on target servers.
Installation
# On your control machine (local or CI server)
pip install ansible
# Or via apt
sudo apt install -y ansible
Inventory
Define your servers:
# inventory/hosts
[web]
web1 ansible_host=198.51.100.10
web2 ansible_host=198.51.100.11
[db]
db1 ansible_host=198.51.100.20
[all:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3
Ad-Hoc Commands
# Ping all servers
ansible all -i inventory/hosts -m ping
# Check uptime
ansible web -i inventory/hosts -a "uptime"
# Install a package
ansible web -i inventory/hosts -m apt -a "name=nginx state=present" --become
Playbooks
# playbooks/setup-web.yml
---
- name: Configure web servers
hosts: web
become: yes
vars:
domain: example.com
tasks:
- name: Update apt cache
apt:
update_cache: yes
cache_valid_time: 3600
- name: Install packages
apt:
name:
- nginx
- php8.3-fpm
- php8.3-mysql
- certbot
state: present
- name: Copy Nginx config
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/sites-available/{{ domain }}.conf
notify: Reload Nginx
- name: Enable site
file:
src: /etc/nginx/sites-available/{{ domain }}.conf
dest: /etc/nginx/sites-enabled/{{ domain }}.conf
state: link
notify: Reload Nginx
- name: Ensure Nginx is running
service:
name: nginx
state: started
enabled: yes
handlers:
- name: Reload Nginx
service:
name: nginx
state: reloaded
# Run the playbook
ansible-playbook -i inventory/hosts playbooks/setup-web.yml
Roles
Organize reusable configurations:
roles/
├── common/
│ └── tasks/main.yml # Base packages, users, SSH
├── nginx/
│ ├── tasks/main.yml # Install and configure
│ ├── templates/nginx.conf.j2
│ └── handlers/main.yml
└── mysql/
├── tasks/main.yml
└── templates/my.cnf.j2
# playbooks/site.yml
- hosts: web
roles:
- common
- nginx
Idempotency
Ansible tasks are idempotent — running them twice produces the same result:
# This only installs if nginx is not already present
- name: Install Nginx
apt:
name: nginx
state: present
| Concept | Meaning |
|---|---|
| Idempotent | Safe to run repeatedly |
| Declarative | Describe desired state, not steps |
| Agentless | Only needs SSH access |
| Handlers | Run only when notified (on change) |
Tip Start with ad-hoc commands to learn, then graduate to playbooks. Don't jump to roles until you have 3+ playbooks with shared tasks.