Ansible Deployment Methods and Basic Usage
1. Method One: Install Using Package Manager (Recommended)
Ubuntu/Debian:
sudo apt update
sudo apt install ansible -y
CentOS/RHEL/Rocky Linux:
# For CentOS 7/RHEL 7
sudo yum install epel-release -y
sudo yum install ansible -y
# For CentOS 8+/RHEL 8+
sudo dnf install epel-release -y
sudo dnf install ansible -y
Method Two: Install from Source
git clone https://github.com/ansible/ansible.git
cd ansible
source ./hacking/env-setup
pip3 install -r requirements.txt
2. Verify Installation
ansible --version
3. Basic Configuration of Ansible
Create Basic Directory Structure
mkdir -p ~/ansible/{inventory,group_vars,host_vars,roles,playbooks}
cd ~/ansible
Configure ansible.cfg
cat > ansible.cfg << EOF
[defaults]
inventory = inventory/hosts
host_key_checking = False
remote_user = root
private_key_file = ~/.ssh/id_rsa
[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False
EOF
Create Inventory File
cat > inventory/hosts << EOF
[web_servers]
web1.example.com
web2.example.com ansible_port=2222 # Custom SSH port
[db_servers]
db1.example.com
db2.example.com
[all:vars]
ansible_ssh_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_rsa
EOF
Generate SSH Key Pair on Machine A
# Generate RSA key pair (recommended)
ssh-keygen -t rsa -b 4096 -C "ansible-control-node" -f ~/.ssh/id_rsa -N ""
# Or generate ED25519 key (more secure, shorter)
ssh-keygen -t ed25519 -C "ansible-control-node" -f ~/.ssh/id_ed25519 -N ""
# View generated keys
ls -la ~/.ssh/
# id_rsa # Private key (keep secret!)
# id_rsa.pub # Public key (distribute to other machines)
Method One: Use ssh-copy-id for Automatic Distribution (Recommended)
Single Machine Distribution
# Basic usage
ssh-copy-id -i ~/.ssh/id_rsa.pub user@target_host
# Example specifying port
ssh-copy-id -i ~/.ssh/id_rsa.pub -p 2222 [email protected]
# Using another key
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]
Batch Distribution to Multiple Machines
# Create host list file
cat > hosts.txt << EOF
user1@host1
user2@host2:2222
[email protected]
[email protected]
EOF
# Use loop for batch distribution
for host in $(cat hosts.txt); do
echo "Distributing public key to: $host"
ssh-copy-id -i ~/.ssh/id_rsa.pub $host
done
Method Two: Manual Public Key Distribution
Step 1: Copy Public Key Content
# Display public key content
cat ~/.ssh/id_rsa.pub
# Or copy to clipboard (Linux)
cat ~/.ssh/id_rsa.pub | xclip -selection clipboard
Step 2: Add Public Key on Target Machine
# Log in to target machine
ssh user@target_host
# Create .ssh directory (if it doesn't exist)
mkdir -p ~/.ssh
chmod 700 ~/.ssh
# Add public key to authorized_keys
echo "ssh-rsa AAAAB3NzaC1yc2E... full public key content" >> ~/.ssh/authorized_keys
# Set correct permissions
chmod 600 ~/.ssh/authorized_keys
# Exit
exit
4. Common Ansible Commands
Basic Commands
# Test connection
ansible all -m ping
# Check host list
ansible all --list-hosts
# Execute shell command
ansible web_servers -m shell -a "uptime"
# File transfer
ansible web_servers -m copy -a "src=/local/file.txt dest=/remote/file.txt"
# Package management
ansible web_servers -m apt -a "name=nginx state=present" # Ubuntu/Debian
ansible web_servers -m yum -a "name=nginx state=present" # CentOS/RHEL
Common Module Commands
# Service management
ansible web_servers -m service -a "name=nginx state=started enabled=yes"
# User management
ansible all -m user -a "name=john state=present groups=wheel"
# File permissions
ansible web_servers -m file -a "path=/etc/nginx/nginx.conf owner=root group=root mode=0644"
# Directory creation
ansible web_servers -m file -a "path=/opt/myapp state=directory"
# Get system information
ansible all -m setup # Display all facts
ansible all -m setup -a "filter=ansible_distribution*"
Playbook Related Commands
# Run playbook
ansible-playbook site.yml
# Check playbook syntax
ansible-playbook --syntax-check site.yml
# Dry run (does not actually execute)
ansible-playbook --check site.yml
# Run with specified tags
ansible-playbook site.yml --tags "deploy,config"
# Skip tags
ansible-playbook site.yml --skip-tags "restart"
# Specify inventory file
ansible-playbook -i custom_inventory site.yml
# Limit execution hosts
ansible-playbook site.yml --limit "web_servers"
Execute Specific Tasks
# Execute command on specific host
ansible-playbook -i inventory/hosts --limit "web1.example.com" playbook.yml
# Use extra variables
ansible-playbook site.yml -e "version=1.0.0 env=production"
# Read variables from file
ansible-playbook site.yml -e "@vars.yml"
5. Practical Examples
Basic Playbook Example
# site.yml
---
- name: Configure Web Server
hosts: web_servers
become: yes
vars:
http_port: 80
max_clients: 200
tasks:
- name: Install nginx
apt:
name: nginx
state: present
update_cache: yes
when: ansible_os_family == "Debian"
- name: Start nginx service
service:
name: nginx
state: started
enabled: yes
- name: Deploy web page file
copy:
src: files/index.html
dest: /var/www/html/index.html
owner: www-data
group: www-data
mode: '0644'
Common Ad-hoc Command Examples
# Restart services in bulk
ansible web_servers -m service -a "name=nginx state=restarted"
# Check disk usage
ansible all -m shell -a "df -h"
# View logs
ansible web_servers -m shell -a "tail -20 /var/log/nginx/access.log"
# Bulk add users
ansible all -m user -a "name=deployer groups=wheel shell=/bin/bash"
# Deploy public key
ansible all -m authorized_key -a "user=root key='{{ lookup('file', '~/.ssh/id_rsa.pub') }}'"
6. Troubleshooting Commands
# Increase verbosity
ansible-playbook site.yml -v
ansible-playbook site.yml -vvv # More detailed
# Test connectivity
ansible all -m ping
# Check fact collection
ansible all -m setup | less
# Check specific variable
ansible all -m debug -a "var=ansible_distribution"