Mastering Ansible on Ubuntu: A Complete Setup Guide for Beginners
Simplify your DevOps automation with this hands-on tutorial covering Ansible installation, configuration, and your first playbook on Ubuntu
Learn DevOps Automation from Installation to First Playbook
Quick Navigation
Difficulty: Beginner
Estimated Time: 20-30 minutes
Prerequisites: Basic Linux command line knowledge, SSH understanding, Ubuntu system access
What You'll Learn
This tutorial covers essential Ansible concepts and tools:
- Ansible Fundamentals - Understanding automation and configuration management
- Ubuntu Installation - Step-by-step setup on Ubuntu systems
- SSH Configuration - Setting up secure remote access
- Inventory Management - Organizing your target hosts
- First Playbook - Creating and running your first automation task
- Best Practices - Security and production considerations
Prerequisites
- Basic Linux command line knowledge
- SSH understanding and key-based authentication
- Ubuntu system access (20.04+ or 22.04+)
- Network connectivity between systems
Related Tutorials
- Main Tutorials Hub - Step-by-step implementation guides
- DevOps Tutorials - Infrastructure automation and deployment guides
- Kubernetes Tutorials - Container orchestration guides
Introduction
Ansible is a powerful open-source tool designed for automation, configuration management, and application deployment. Whether you're managing one server or a thousand, Ansible helps reduce manual operations and speeds up deployments. In this easy-to-follow guide, we'll walk you through installing and configuring Ansible on Ubuntu 20.04+ / 22.04+.
Step-by-Step Ansible Installation & Configuration Guide on Ubuntu
Step 1: Update Your System
Keep your system healthy and up to date
sudo apt update && sudo apt upgrade -y
Step 2: Install Ansible
Quick Install
sudo apt install software-properties-common -y
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install ansible -y
Step 3: Verify Installation
ansible --version
You should see the installed Ansible version info
Expected Output:
ansible [core 2.15.x]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
ansible collection location = /home/user/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/bin/ansible
python version = 3.10.x (main, Mar 15 2023, 20:47:15) [GCC 11.3.0]
jinja version = 3.0.1
libyaml = True
Step 4: Configure Ansible Inventory
Edit the default inventory file:
sudo nano /etc/ansible/hosts
Example Inventory
[web]
192.168.1.10
web1.example.com
[db]
192.168.1.20
[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_rsa
Inventory Structure Explained:
[web]- Group for web servers[db]- Group for database servers[all:vars]- Variables applied to all hostsansible_user- Default SSH user
Step 5: Test Connectivity
Test if Ansible can reach your hosts:
ansible all -m ping
Expected Output:
192.168.1.10 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.1.20 | SUCCESS => {
"changed": false,
"ping": "pong"
}
Step 6: Create Your First Playbook
Create a simple playbook to install and configure a web server:
mkdir ~/ansible-playbooks
cd ~/ansible-playbooks
nano web-server.yml
Web Server Playbook
---
- name: Install and configure web server
hosts: web
become: yes
tasks:
- name: Install Apache
apt:
name: apache2
state: present
update_cache: yes
- name: Start and enable Apache
service:
name: apache2
state: started
enabled: yes
- name: Create custom index page
copy:
content: |
<html>
<body>
<h1>Welcome to my Ansible-managed server!</h1>
<p>This page was created by Ansible automation.</p>
</body>
</html>
dest: /var/www/html/index.html
owner: www-data
group: www-data
mode: '0644'
Step 7: Run Your Playbook
Execute the playbook:
ansible-playbook web-server.yml
Expected Output:
PLAY [Install and configure web server] *******************************
TASK [Install Apache] ************************************************
changed: [192.168.1.10]
TASK [Start and enable Apache] **************************************
changed: [192.168.1.10]
TASK [Create custom index page] *************************************
changed: [192.168.1.10]
PLAY RECAP **********************************************************
192.168.1.10 : ok=3 changed=3 unreachable=0 failed=0
Step 8: Verify the Results
Check if your web server is running:
curl http://192.168.1.10
You should see your custom HTML page.
Advanced Ansible Configuration
Custom Ansible Configuration
Create a custom configuration file:
mkdir ~/.ansible
nano ~/.ansible/ansible.cfg
Custom Configuration
[defaults]
inventory = ~/ansible-inventory
remote_user = ubuntu
private_key_file = ~/.ssh/id_rsa
host_key_checking = False
timeout = 30
gathering = smart
fact_caching = memory
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
pipelining = True
Using Variables in Playbooks
Create a more advanced playbook with variables:
---
- name: Configure web servers with variables
hosts: web
become: yes
vars:
web_packages:
- apache2
- nginx
web_user: www-data
web_group: www-data
tasks:
- name: Install web packages
apt:
name: "{{ web_packages }}"
state: present
update_cache: yes
- name: Create web directory
file:
path: /var/www/html
state: directory
owner: "{{ web_user }}"
group: "{{ web_group }}"
mode: '0755'
Using Templates
Create a template for dynamic configuration:
mkdir ~/ansible-playbooks/templates
nano ~/ansible-playbooks/templates/vhost.conf.j2
Virtual Host Template
<VirtualHost *:80>
ServerName {{ server_name }}
DocumentRoot {{ document_root }}
<Directory {{ document_root }}>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/{{ server_name }}_error.log
CustomLog ${APACHE_LOG_DIR}/{{ server_name }}_access.log combined
</VirtualHost>
Best Practices
1. Security Considerations
- SSH Key Management: Use key-based authentication instead of passwords
- User Permissions: Run Ansible with appropriate user permissions
- Inventory Security: Keep inventory files secure and restrict access
- Vault Encryption: Use Ansible Vault for sensitive data
2. Performance Optimization
- Fact Caching: Enable fact caching for faster execution
- Parallel Execution: Use
forkssetting for concurrent connections - SSH Pipelining: Enable SSH pipelining for better performance
- Gathering: Use
gathering = smartfor intelligent fact collection
3. Playbook Organization
- Directory Structure: Organize playbooks by function or environment
- Role-Based Design: Use Ansible roles for reusable components
- Variable Management: Separate variables into group_vars and host_vars
- Documentation: Document your playbooks and roles
4. Testing and Validation
- Syntax Checking: Always validate playbook syntax before running
- Dry Runs: Use
--checkmode to preview changes - Staging Environment: Test playbooks in staging before production
- Version Control: Use Git to track playbook changes
Troubleshooting Common Issues
Connection Problems
Issue: Host unreachable Solution: Check SSH connectivity and firewall settings
# Test SSH connection manually
ssh ubuntu@192.168.1.10
# Check if port 22 is open
telnet 192.168.1.10 22
Permission Issues
Issue: Permission denied errors Solution: Ensure proper SSH key permissions and sudo access
# Fix SSH key permissions
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
# Test sudo access on target host
ssh ubuntu@192.168.1.10 'sudo whoami'
Python Version Issues
Issue: Python version compatibility Solution: Ensure target hosts have compatible Python versions
# Check Python version on target host
ansible all -m raw -a "python3 --version"
# Use raw module for hosts without Python
ansible all -m raw -a "apt-get update && apt-get install -y python3"
Conclusion
You've successfully learned how to set up and use Ansible on Ubuntu! This powerful automation tool will help you manage your infrastructure more efficiently and consistently.
Key Takeaways:
- Installation: Easy setup through Ubuntu package manager
- Configuration: Simple inventory and configuration management
- Playbooks: Declarative automation with YAML syntax
- Best Practices: Security, performance, and organization guidelines
Next Steps:
- Practice: Create more complex playbooks for your use cases
- Explore Roles: Learn about Ansible roles for reusable components
- Advanced Features: Discover variables, templates, and conditionals
- Integration: Integrate Ansible with your CI/CD pipelines
Start with simple automation tasks and gradually build more complex workflows. Ansible's learning curve is gentle, making it perfect for both beginners and experienced DevOps engineers.
Tags: #Ansible #DevOps #Automation #Ubuntu #ConfigurationManagement #InfrastructureAsCode #SSH #Playbooks #LinuxAdmin #Sysadmin