Ansible is a powerful open-source automation tool that can help you manage servers, configure systems, and deploy applications at scale. In this comprehensive guide, we'll explore everything you need to know to get started with Ansible.
What is Ansible?
Ansible is an agentless automation platform that simplifies:
- Configuration Management
- Application Deployment
- Task Automation
- IT Orchestration
- Cloud Provisioning
Unlike other configuration management tools, Ansible doesn't require any special software to be installed on the nodes it manages. It uses SSH for secure connections and Python for executing its modules.
Why Choose Ansible?
- Agentless Architecture: No need to install special software on managed nodes
- Simple Syntax: Uses YAML, which is human-readable and easy to learn
- Idempotent: Running the same playbook multiple times won't change the result
- Large Community: Extensive collection of pre-built modules and roles
- Push-Based: Changes are pushed from a central location
Installation and Setup
Installing Ansible
On Ubuntu/Debian:
sudo apt update
sudo apt install ansible
On CentOS/RHEL:
sudo yum install epel-release
sudo yum install ansible
On macOS:
brew install ansible
Basic Configuration
The main Ansible configuration file is located at /etc/ansible/ansible.cfg
. Here's a basic configuration:
[defaults]
inventory = ./inventory
remote_user = your_ssh_user
private_key_file = ~/.ssh/id_rsa
host_key_checking = False
Understanding Inventory Files
Inventory files define the hosts and groups that Ansible will manage. They can be in INI or YAML format.
Basic Inventory (inventory.ini)
[webservers]
web1.example.com
web2.example.com
[dbservers]
db1.example.com
db2.example.com
[development]
dev.example.com ansible_host=192.168.1.100
[all:vars]
ansible_python_interpreter=/usr/bin/python3
YAML Inventory (inventory.yml)
all:
children:
webservers:
hosts:
web1.example.com:
web2.example.com:
dbservers:
hosts:
db1.example.com:
db2.example.com:
Ad-Hoc Commands
Ad-hoc commands are one-line tasks that you can run against your hosts:
# Ping all servers
ansible all -m ping
# Check disk space
ansible webservers -a "df -h"
# Update apt cache (Ubuntu/Debian)
ansible webservers -m apt -a "update_cache=yes" --become
Understanding Tasks
Tasks are the basic unit of work in Ansible. They define what actions should be performed.
Example task:
- name: Install nginx
apt:
name: nginx
state: present
become: yes
- name: Start nginx service
service:
name: nginx
state: started
enabled: yes
become: yes
Creating Playbooks
Playbooks are YAML files containing a list of plays. Each play is a set of tasks to be executed on specific hosts.
Basic Playbook (web_setup.yml)
---
- name: Configure web servers
hosts: webservers
become: yes
tasks:
- name: Install required packages
apt:
name: "{{ item }}"
state: present
update_cache: yes
loop:
- nginx
- php-fpm
- mysql-client
- name: Copy nginx configuration
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart nginx
- name: Start and enable services
service:
name: "{{ item }}"
state: started
enabled: yes
loop:
- nginx
- php-fpm
handlers:
- name: Restart nginx
service:
name: nginx
state: restarted
Working with Variables
Variables in Ansible can be defined in multiple places:
In Playbooks
---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
In Variable Files (group_vars/webservers.yml)
---
http_port: 80
max_clients: 200
app_version: "1.2.3"
Using Variables in Templates
# templates/nginx.conf.j2
server {
listen {{ http_port }};
root /var/www/html;
location / {
# configuration here
}
}
Roles
Roles are ways of automatically loading certain vars, files, tasks, handlers, and other Ansible artifacts based on a known file structure.
Role Directory Structure
roles/
webserver/
tasks/
main.yml
handlers/
main.yml
templates/
nginx.conf.j2
vars/
main.yml
defaults/
main.yml
meta/
main.yml
Using Roles in Playbooks
---
- hosts: webservers
roles:
- webserver
- database
- { role: app, vars: { app_port: 3000 } }
Best Practices
-
Use Version Control
- Keep your Ansible code in a git repository
- Use meaningful commit messages
Directory Structure
ansible-project/
├── inventory/
│ ├── production.yml
│ └── staging.yml
├── group_vars/
│ ├── all.yml
│ └── webservers.yml
├── roles/
│ └── webserver/
├── playbooks/
│ ├── site.yml
│ └── webserver.yml
└── ansible.cfg
-
Tags
- Use tags to run specific parts of your playbooks
tasks:
- name: Install packages
apt:
name: nginx
state: present
tags: ['packages', 'nginx']
-
Vault
- Use ansible-vault for sensitive data
# Encrypt file
ansible-vault encrypt secrets.yml
# Edit encrypted file
ansible-vault edit secrets.yml
Common Modules
- File Operations
- name: Create directory
file:
path: /app/data
state: directory
mode: '0755'
- name: Copy file
copy:
src: files/app.conf
dest: /etc/app/app.conf
- Package Management
- name: Install packages
package:
name: "{{ item }}"
state: present
loop:
- git
- curl
- vim
- Service Management
- name: Ensure service is running
service:
name: nginx
state: started
enabled: yes
Debugging
- Verbose Output
ansible-playbook playbook.yml -vvv
- Debug Module
- name: Debug variable
debug:
var: http_port
msg: "The HTTP port is {{ http_port }}"
Conclusion
Ansible is a powerful tool for automation that can significantly improve your infrastructure management workflow. This tutorial covered the basics, but there's much more to explore, including:
- Dynamic inventory
- Custom modules
- Error handling
- Conditionals and loops
- Advanced playbook features
Remember to always test your playbooks in a staging environment before running them in production.
Additional Resources
- Official Ansible Documentation
- Ansible Galaxy for community roles
- Ansible GitHub Repository
Top comments (0)