Ansible is an open-source automation tool that simplifies configuration management, application deployment, and task automation. Key characteristics:
1. Python-based infrastructure automation platform
2. Agentless architecture using SSH protocol
3. Supports multi-node orchestration and parallel execution
Environment Setup
| Host | IP Address |
|---|---|
| Control Node | 192.168.4.11 |
| Managed Node | 192.168.4.12 |
Installation
# On control node
yum install ansible
# On managed nodes
yum install libselinux-python
Core Ansible Components
Configuration Files
# /etc/ansible/ansible.cfg (Main configuration)
[defaults]
inventory = /etc/ansible/hosts
host_key_checking = False
log_path = /var/log/ansible.log
Inventory Management
[web_servers]
192.168.4.12
192.168.4.13
[db_servers]
db1.example.com
db2.example.com
Authentication Methods
SSH Key Authentication
# Generate SSH key pair
ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/ansible_key
# Distribute public key
ssh-copy-id -i ~/.ssh/ansible_key.pub user@remote_host
Password Authentication
[servers]
192.168.4.12 ansible_user=admin ansible_ssh_pass=secure123
Common Modules
System Operations
# Package management
ansible web -m yum -a "name=nginx state=present"
# Service control
ansible web -m systemd -a "name=nginx enabled=yes state=started"
File Management
# File transfer
ansible web -m copy -a "src=/local/path dest=/remote/path owner=root mode=0644"
# Directory creation
ansible web -m file -a "path=/data/logs state=directory owner=www group=www"
Playbook Basics
---
- hosts: webservers
become: yes
tasks:
- name: Ensure Nginx is installed
yum:
name: nginx
state: present
- name: Start Nginx service
service:
name: nginx
state: started
enabled: yes
Variables and Templates
# Variable definition
vars:
http_port: 8080
max_workers: 4
# Template usage
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
Conditional Execution
tasks:
- name: Install EPEL on CentOS
yum: name=epel-release state=present
when: ansible_distribution == "CentOS"
Loops and Iterations
tasks:
- name: Create multiple users
user:
name: "{{ item.name }}"
group: "{{ item.group }}"
loop:
- { name: 'dev1', group: 'developers' }
- { name: 'dev2', group: 'developers' }
Error Handling
tasks:
- name: Attempt risky operation
command: /usr/bin/risky_command
ignore_errors: yes
Roles for Modularizatino
roles/
├── common
│ ├── tasks
│ ├── handlers
│ └── vars
└── webserver
├── templates
└── files
Practical Examples
NFS Server Deployment
- hosts: storage
tasks:
- name: Install NFS packages
yum: name=nfs-utils state=present
- name: Configure exports
copy: src=exports.j2 dest=/etc/exports
Web Server Configuration
- hosts: web
handlers:
- name: restart apache
service: name=httpd state=restarted
tasks:
- name: Install Apache
yum: name=httpd state=present