Ansible is an open-source automation tool used for configuration management, application deployment, and task automation. It is agentless, meaning it only requires SSH access to manage systems.
sudo apt update && sudo apt install -y ansible
sudo dnf install -y ansible
brew install ansible
ansible --version
A well-structured Ansible project follows this layout:
ansible/
├── ansible.cfg # Configuration file
├── inventory/ # Inventory files
│ ├── hosts.ini # List of managed hosts
├── playbooks/ # Playbooks for automation
│ ├── setup.yml # Example playbook
├── roles/ # Reusable roles
│ ├── example_role/ # Example role
│ │ ├── tasks/ # Task definitions
│ │ ├── handlers/ # Handlers (e.g., restart services)
│ │ ├── templates/ # Jinja2 templates
│ │ ├── defaults/ # Default variables
│ │ ├── vars/ # Role-specific variables
│ │ ├── files/ # Static files
To create a structured project, run:
mkdir -p ansible/{inventory,playbooks,roles}
cd ansible
ansible-galaxy init roles/example_role
This initializes roles/example_role with the correct structure.
ansible -i inventory/hosts.ini all -m ping
ansible -i inventory/hosts.ini all -m command -a "uptime"
ansible-playbook -i inventory/hosts.ini playbooks/setup.yml
ansible-playbook -i inventory/hosts.ini set_timezone.yml --ask-become-pass
A basic playbook (playbooks/setup.yml):
- name: Example Playbook
hosts: all
become: true
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
Ansible templates use Jinja2, allowing dynamic content generation.
roles/example_role/templates/nginx.conf.j2):server {
listen 80;
server_name {{ server_name }};
location / {
root {{ document_root }};
}
}
- name: Deploy Nginx Configuration
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart Nginx
This cheat sheet provides a quick reference for getting started with Ansible! 🚀