1
Ansible Fundamentals
Ansible Fundamentals
Ansible is an open-source automation tool that simplifies configuration management, application deployment, and task automation.
What is Ansible?
Ansible is an agentless automation platform that uses SSH to communicate with managed nodes. It uses a simple YAML syntax called Ansible Playbooks to describe automation jobs.
Key Concepts
Inventory
An inventory file defines the hosts and groups of hosts that Ansible manages.
ini
# inventory.ini
[webservers]
web1.example.com
web2.example.com
[databases]
db1.example.com
Playbooks
Playbooks are YAML files that define the automation tasks.
yaml
---
- name: Install and start Apache
hosts: webservers
become: yes
tasks:
- name: Install Apache
apt:
name: apache2
state: present
- name: Start Apache
service:
name: apache2
state: started
enabled: yes
Modules
Ansible modules are units of code that provide specific functionality.
yaml
- name: Create a user
user:
name: john
state: present
shell: /bin/bash
Installing Ansible
bash
# Ubuntu/Debian
sudo apt update
sudo apt install ansible
# CentOS/RHEL
sudo yum install ansible
# Using pip
pip install ansible
Running Your First Playbook
bash
# Run a playbook
ansible-playbook -i inventory.ini playbook.yml
# Run with verbose output
ansible-playbook -i inventory.ini playbook.yml -v
# Dry run (check mode)
ansible-playbook -i inventory.ini playbook.yml --check
Ansible Ad-Hoc Commands
bash
# Ping all hosts
ansible all -i inventory.ini -m ping
# Run a command
ansible webservers -i inventory.ini -m shell -a "uptime"
# Copy a file
ansible webservers -i inventory.ini -m copy -a "src=file.txt dest=/tmp/"
Best Practices
- Use version control for playbooks
- Keep playbooks simple and focused
- Use roles for complex configurations
- Test with --check before applying
- Use variables for flexibility
- Document your playbooks