Ansible Automation: Your First Playbook
Get started with Ansible for IT automation. Learn how to install Ansible, create an inventory, write your first playbook, and automate common server tasks.
Ansible Automation: Your First Playbook
Ansible lets you automate server configuration, deployments, and repetitive IT tasks without installing agents on target machines. It uses SSH and YAML — nothing complicated.
Prerequisites
- A Linux control node (your workstation or a jump box)
- One or more target servers with SSH access
- Python 3 installed on all machines
Step 1: Install Ansible
# Ubuntu/Debian
sudo apt update
sudo apt install ansibleOr via pip
pip3 install ansibleVerify
ansible --versionStep 2: Create Your Inventory
Create inventory.ini:
[webservers]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11[dbservers]
db1 ansible_host=192.168.1.20
[all:vars]
ansible_user=admin
ansible_ssh_private_key_file=~/.ssh/id_rsa
Test connectivity:
ansible all -i inventory.ini -m pingStep 3: Write Your First Playbook
Create setup-webserver.yml:
---
- name: Set up web servers
hosts: webservers
become: yes tasks:
- name: Update apt cache
apt:
update_cache: yes
cache_valid_time: 3600
- name: Install Nginx
apt:
name: nginx
state: present
- name: Start and enable Nginx
systemd:
name: nginx
state: started
enabled: yes
- name: Copy custom index page
copy:
content: |
<h1>Hello from {{ inventory_hostname }}</h1>
<p>Deployed by Ansible</p>
dest: /var/www/html/index.html
- name: Open firewall port 80
ufw:
rule: allow
port: "80"
proto: tcp
Run it:
ansible-playbook -i inventory.ini setup-webserver.ymlStep 4: Use Variables and Templates
Create group_vars/webservers.yml:
http_port: 80
server_admin: [email protected]Create a Jinja2 template templates/nginx.conf.j2:
server {
listen {{ http_port }};
server_name {{ inventory_hostname }};
root /var/www/html; location / {
try_files $uri $uri/ =404;
}
}
Use the template in your playbook:
- name: Deploy Nginx config
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/sites-available/default
notify: Restart Nginx handlers:
- name: Restart Nginx
systemd:
name: nginx
state: restarted
Step 5: Use Roles for Organization
ansible-galaxy init roles/webserverThis creates a structured directory:
roles/webserver/
tasks/main.yml
handlers/main.yml
templates/
files/
vars/main.yml
defaults/main.ymlEssential Ansible Commands
ansible all -m ping— Test connectivityansible-playbook playbook.yml --check— Dry runansible-playbook playbook.yml --diff— Show changesansible-playbook playbook.yml --limit web1— Run on specific hostansible-vault encrypt secrets.yml— Encrypt sensitive files
Conclusion
You've written your first Ansible playbook and learned the core concepts. Ansible scales from managing 2 servers to 2000 with the same simple YAML syntax. Start automating your repetitive tasks today.