Installing Ansible
You can install Ansible on any Linux system. Below are the basic steps to get started:
Step 1: Update the System
sudo apt updatesudo apt upgrade -y
Step 2: Install Ansible
sudo apt install ansible -y
Step 3: Verify Installation
ansible --version
You should now see the Ansible version along with Python dependencies.
Step 4: Configure Inventory
Ansible uses an inventory file (default: /etc/ansible/hosts) to define the list of servers it will manage.
Example:
[webservers]
192.168.1.10
192.168.1.11
Step 5: Setup SSH Access
Ensure password less SSH is configured between your Ansible master (control node) and managed nodes.
ssh-keygenssh-copy-id [email protected]
Creating an Ansible Playbook
A playbook is the heart of Ansible. It defines tasks that Ansible performs on remote hosts. Playbooks are written in YAML format and can have one or multiple "plays."
Here's the basic structure:
---
- hosts: webservers
become yes
name: Install and Configure Nginx
tasks:
- name: Install Nginx
apt:
name: nginx
state: latest
- name: Start Nginx Service
service:
name: nginx
state: started
Save the above file as nginx_playbook.yml.
Understanding Playbook Structure
A playbook can contain:
- hosts → Target systems (from your inventory)
- tasks → The actions to perform
- modules → Built-in Ansible components (e.g., apt, copy, service)
- handlers → Triggered by tasks and run at the end (like restarting services)
Syntax Check
Before executing your playbook, always perform a syntax check to ensure there are no YAML or logical errors.
ansible-playbook nginx_playbook.yml --syntax-check
If everything is correct, you'll get:
playbook: nginx_playbook.yml
Running the Playbook
Now, execute the playbook using the following command:
ansible-playbook nginx_playbook.yml
Ansible will connect to your hosts via SSH and run each task in the order they're listed. You'll see a summary like:
PLAY RECAP
******************************************************************
192.168.1.10 : ok=3 changed=2 unreachable=0 failed=0
Conclusion
Ansible makes infrastructure automation simple and scalable. From installing packages to deploying full-scale applications, playbooks help you manage your environment efficiently.