Using Ansible to Automate Linux Server Setup
Introduction
Ansible is a powerful automation tool that simplifies server setup and configuration. It allows you to define configurations as code and apply them consistently across multiple machines. This guide will walk you through using Ansible to automate Linux server setup.
Step 1: Install Ansible
-
Update your package list and install Ansible:
sudo apt update && sudo apt install ansible -y
-
Verify the installation:
ansible --version
Step 2: Configure Ansible Inventory
-
Define the servers to manage in the inventory file:
sudo nano /etc/ansible/hosts
-
Example inventory:
[web]
server1 ansible_host=192.168.1.10
server2 ansible_host=192.168.1.11
``
[db]
server3 ansible_host=192.168.1.12
-
Save and close the file.
Step 3: Set Up SSH Access
-
Ensure passwordless SSH authentication:
ssh-keygen -t rsa -b 4096
ssh-copy-id [email protected]
-
Test SSH access:
Step 4: Create an Ansible Playbook
-
Create a playbook to install basic packages:
sudo nano setup-server.yml
-
Example playbook:
- hosts: all
become: yes
tasks:
name: Update system packages
apt:
update_cache: yes
name: Install common packages
apt:
name:
- vim
- curl
- htop
state: present
-
Save and close the file.
Step 5: Run the Ansible Playbook
-
Execute the playbook on all servers:
ansible-playbook -i /etc/ansible/hosts setup-server.yml
-
Verify package installation by logging into a server:
which vim curl htop
Conclusion
Using Ansible simplifies server setup and ensures consistent configurations across multiple machines. As you advance, you can create more complex playbooks to manage services, security, and application deployments.