Step 1: Update Your System
Ensure your system is up to date:
sudo apt update && sudo apt upgrade -y
Step 2: Install Ansible
2.1: Add Ansible PPA
Ansible is included in the Ubuntu repositories, but using the official Ansible PPA ensures you get the latest version:
sudo apt install -y software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
2.2: Install Ansible
sudo apt install -y ansible
Step 3: Verify Ansible Installation
Check the installed version:
ansible --version
Step 4: Configure Ansible
Ansible uses an inventory file to define the hosts it manages. By default, the inventory file is located at /etc/ansible/hosts
.
4.1: Edit the Inventory File
Open the inventory file:
sudo nano /etc/ansible/hosts
Add managed hosts (IP addresses or domain names) to the file. For example:
[webservers]
192.168.1.10
192.168.1.11
[dbservers]
192.168.1.20
Save and exit the file.
Step 5: Test Ansible Connectivity
5.1: Ensure SSH Access
Ansible connects to managed nodes using SSH. Ensure SSH is configured:
-
Install OpenSSH server if not already installed:
sudo apt install -y openssh-server
-
Test SSH access to a managed node:
ssh username@192.168.1.10
5.2: Test Connection with Ansible
Use the ping
module to test connectivity to all hosts:
ansible all -m ping
Output should indicate success:
192.168.1.10 | SUCCESS => {
"changed": false,
"ping": "pong"
}
Step 6: Create a Simple Playbook
Ansible uses playbooks (written in YAML) to define automation tasks.
6.1: Create a Playbook
Create a file named example-playbook.yml
:
nano example-playbook.yml
Add the following content to install Apache on the webservers:
- name: Install Apache on Webservers
hosts: webservers
become: yes
tasks:
- name: Install Apache
apt:
name: apache2
state: present
6.2: Run the Playbook
Execute the playbook:
ansible-playbook example-playbook.yml
Step 7: Optional Ansible Configuration
7.1: Change Default Configuration
Edit the Ansible configuration file:
sudo nano /etc/ansible/ansible.cfg
You can modify settings like:
-
Default Inventory: Change the default inventory file.
-
Privilege Escalation: Enable
become
for privilege escalation. -
Remote User: Specify the SSH user.
For example:
[defaults]
inventory = /etc/ansible/hosts
remote_user = your-username
Step 8: Common Troubleshooting Tips
-
SSH Key Authentication: Use SSH keys for passwordless authentication:
ssh-keygen -t rsa ssh-copy-id username@192.168.1.10
-
Verbose Output: Run commands with
-vvv
to get detailed logs:ansible all -m ping -vvv
With Ansible installed and configured, you can now automate tasks and manage multiple servers efficiently. Let me know if you need help with specific use cases or modules!