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

  1. Update your package list and install Ansible:

    sudo apt update && sudo apt install ansible -y

  2. Verify the installation:

    ansible --version


Step 2: Configure Ansible Inventory

  1. Define the servers to manage in the inventory file:

    sudo nano /etc/ansible/hosts

  2. 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

  3. Save and close the file.


Step 3: Set Up SSH Access

  1. Ensure passwordless SSH authentication:

    ssh-keygen -t rsa -b 4096

    ssh-copy-id [email protected]

  2. Test SSH access:

    ssh [email protected]


Step 4: Create an Ansible Playbook

  1. Create a playbook to install basic packages:

    sudo nano setup-server.yml

  2. 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

  3. Save and close the file.


Step 5: Run the Ansible Playbook

  1. Execute the playbook on all servers:

    ansible-playbook -i /etc/ansible/hosts setup-server.yml

  2. Verify package installation by logging into a server:

    ssh [email protected]

    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.