Ansibleπ
Automate IT infrastructure with ease
Introductionπ
Ansible is an automation tool that helps you manage servers, deploy applications, and configure systems. It uses YAML for its playbooks, making it easy to read and write.
Key Features:
- Agentless: No software needed on managed nodes.
- Idempotent: Running the same playbook multiple times wonβt break things.
- Declarative: You describe the desired state, and Ansible figures out how to get there.
Installationπ
Install Ansible on your control machine
Key Conceptsπ
-
Inventory: A file that lists the servers (nodes) you want to manage.
-
Playbooks: YAML files that define tasks to be executed.
-
Modules: Pre-built functions (e.g.,
apt
,copy
,service
) to perform tasks. -
Ad-Hoc Commands: One-liners for quick tasks.
Getting Startedπ
- Create an Inventory File: Save this as
inventory.ini
- Test Connectivity
- Write Your First Playbook: Save as
webserver.yml
- hosts: webservers
become: yes # Run tasks as root
tasks:
- name: Install Apache
apt:
name: apache2
state: present
- name: Start Apache service
service:
name: apache2
state: started
enabled: yes
- Run the Playbook
Common Use Casesπ
Copy Filesπ
Create Usersπ
Install Packagesπ
Restart Servicesπ
Best Practicesπ
1. Organize Playbooksπ
- Use roles to group related tasks (e.g.,
webserver
,database
). - Example structure:
playbooks/
βββ inventory.ini
βββ webserver.yml
βββ roles/
βββ webserver/
βββ tasks/
β βββ main.yml
βββ handlers/
β βββ main.yml
βββ templates/
βββ index.html.j2
2. Use Variablesπ
- Define variables in
group_vars
orhost_vars
3. Idemptotencyπ
- Always check if a task idempotent. For Example
4. Error Handlingπ
- block:
- name: Try risky task
command: /bin/false
rescue:
- name: Handle failure
debug:
msg: "Task failed, but we're recovering!"
Troubleshootingπ
Issue | Solution |
---|---|
"SSH connection failed" | Check SSH keys and ansible_user in inventory. |
"Permission denied" | Use become: yes to run tasks as root. |
"Module not found" | Ensure the module is installed (e.g., apt for Debian). |
Pro Tipsπ
- Dry Run: Test Playbooks without making changes
- Tagging Tasks: Run specific tasks using tags
- Use Vault for Secrets: Encrypt sensitive data
See Alsoπ
- Ansible Documentation
- Ansible Galaxy (pre-built roles)