Ansible Automate VPS Configuration Multiple Servers

Table of Contents

  1. What is Ansible and Why Use It?
  2. Installing Ansible on the Control Node
  3. Setting Up SSH Keys for Ansible
  4. Writing Your Inventory: Defining Managed Servers
  5. Your First Playbook: Install Nginx on All Servers
  6. Using Variables and Templates
  7. Organizing with Ansible Roles
  8. Running Ansible in Production
  9. Best Practices for Production
  10. Frequently Asked Questions

If you've ever had to configure multiple VPS instances one by one — installing Nginx, configuring UFW, deploying applications, or running updates — Ansible is the tool that transforms hours of work into minutes. Write a Playbook once, run it across hundreds of servers simultaneously, and get identical results every time.

This guide covers everything from installing Ansible to production best practices, complete with copy-paste Playbook examples.

1. What is Ansible and Why Use It?

Ansible is an open-source IT automation tool developed by Red Hat, used for Configuration Management, Application Deployment, and Orchestration. Its standout feature is being Agentless — no software needs to be installed on the VPS you're managing. SSH is all it needs.

Key Benefits of Ansible

ToolCategoryLanguageAgentlessBest For
AnsibleConfig MgmtYAML✅ YesVPS setup, app deploy, OS config
TerraformInfrastructureHCL✅ YesCloud resource provisioning
ChefConfig MgmtRuby❌ Agent requiredEnterprise, complex workflows
PuppetConfig MgmtPuppet DSL❌ Agent requiredLarge-scale enterprise
SaltStackConfig MgmtPython/YAMLOptionalReal-time event-driven automation

2. Installing Ansible on the Control Node

The Control Node is the machine where Ansible is installed and from which it sends commands to Managed Nodes (your VPS servers). It can be your laptop or a dedicated management VPS.

Note:

Ansible can only be installed on Linux/macOS (Control Node), but managed nodes support both Linux and Windows.

Install on Ubuntu 22.04/24.04

# Update package list
sudo apt update

# Install from official Ansible PPA (newer than default apt)
sudo apt install -y software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install -y ansible

# Verify installation
ansible --version

Install via pip (alternative — always gets latest version)

pip3 install ansible
ansible --version

3. Setting Up SSH Keys for Ansible

Ansible uses SSH to connect to Managed Nodes. SSH Key Authentication must be configured to avoid entering passwords for every operation.

Generate an SSH Key Pair on the Control Node

# Create SSH key (press Enter through all prompts for no passphrase)
ssh-keygen -t ed25519 -C "ansible-key"

# View the public key
cat ~/.ssh/id_ed25519.pub

Copy the Public Key to Each VPS

# Method 1: Use ssh-copy-id (simplest)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@VPS_IP_1
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@VPS_IP_2

# Method 2: Loop for multiple servers
for ip in 203.0.113.1 203.0.113.2 203.0.113.3; do
  ssh-copy-id -i ~/.ssh/id_ed25519.pub user@$ip
done
⚠️ Security Best Practice:

Keep the Ansible SSH key separate from your personal SSH key. Create a dedicated key for automation so it can be revoked independently if needed.

4. Writing Your Inventory: Defining Managed Servers

The Inventory file tells Ansible which servers exist and how they're grouped. Both INI and YAML formats are supported.

INI Format Inventory (simplest)

# inventory.ini
[webservers]
web1 ansible_host=203.0.113.1
web2 ansible_host=203.0.113.2
web3 ansible_host=203.0.113.3

[dbservers]
db1 ansible_host=203.0.113.10
db2 ansible_host=203.0.113.11

[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_ed25519
ansible_python_interpreter=/usr/bin/python3

YAML Format Inventory (recommended for production)

# inventory.yml
all:
  vars:
    ansible_user: ubuntu
    ansible_ssh_private_key_file: ~/.ssh/id_ed25519

  children:
    webservers:
      hosts:
        web1:
          ansible_host: 203.0.113.1
        web2:
          ansible_host: 203.0.113.2
      vars:
        http_port: 80

    dbservers:
      hosts:
        db1:
          ansible_host: 203.0.113.10
      vars:
        db_port: 5432

Test the Inventory with a Ping

# Ping all servers in inventory
ansible all -i inventory.yml -m ping

# Ping only the webservers group
ansible webservers -i inventory.yml -m ping

5. Your First Playbook: Install Nginx on All Servers

A Playbook is a YAML file that defines which tasks to run on which servers, in what order. Think of it as a "recipe" for your servers.

# nginx-setup.yml
---
- name: Install and configure Nginx on webservers
  hosts: webservers
  become: yes  # use sudo

  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Install Nginx
      apt:
        name: nginx
        state: present  # install if not present

    - name: Enable and start Nginx
      systemd:
        name: nginx
        enabled: yes
        state: started

    - name: Allow port 80 through UFW
      ufw:
        rule: allow
        port: '80'
        proto: tcp

    - name: Allow port 443 through UFW
      ufw:
        rule: allow
        port: '443'
        proto: tcp

Running the Playbook

# Dry run first — see what would change without making changes
ansible-playbook -i inventory.yml nginx-setup.yml --check

# Execute for real
ansible-playbook -i inventory.yml nginx-setup.yml

# Run with verbose output
ansible-playbook -i inventory.yml nginx-setup.yml -v
✅ Idempotent Behavior:

Running this Playbook multiple times is safe. If Nginx is already installed and running, Ansible will skip those tasks — no duplicate work.

6. Using Variables and Templates

Variables make Playbooks flexible. Values like ports, paths, and domain names can be defined separately rather than hardcoded throughout each task.

Defining Variables in a Playbook

# deploy-app.yml
---
- name: Deploy Web Application
  hosts: webservers
  become: yes

  vars:
    app_name: myapp
    app_port: 3000
    deploy_path: /var/www/myapp

  tasks:
    - name: Create app directory
      file:
        path: "{{ deploy_path }}"
        state: directory
        owner: www-data
        mode: '0755'

    - name: Copy app files
      copy:
        src: ./app/
        dest: "{{ deploy_path }}/"
        owner: www-data

Using Jinja2 Templates for Config Files

# templates/nginx.conf.j2
server {
    listen 80;
    server_name {{ domain_name }};
    root {{ deploy_path }};

    location / {
        proxy_pass http://localhost:{{ app_port }};
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
# In Playbook
    - name: Create Nginx config from template
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/sites-available/{{ app_name }}
      notify: reload nginx

  handlers:
    - name: reload nginx
      systemd:
        name: nginx
        state: reloaded

7. Organizing with Ansible Roles

As Playbooks grow larger, Roles help divide tasks into reusable, self-contained units — like functions in programming.

Role Directory Structure

roles/
  nginx/
    tasks/
      main.yml      # main tasks
    handlers/
      main.yml      # handlers (e.g., reload nginx)
    templates/
      nginx.conf.j2 # Jinja2 templates
    files/
      index.html    # static files
    vars/
      main.yml      # role-specific variables
    defaults/
      main.yml      # default values (can be overridden)

Generate a Role with ansible-galaxy

# Auto-generate role structure
ansible-galaxy init roles/nginx
ansible-galaxy init roles/mysql
ansible-galaxy init roles/firewall

Using Roles in a Playbook

# site.yml
---
- name: Setup Web Servers
  hosts: webservers
  become: yes
  roles:
    - nginx
    - firewall

- name: Setup Database Servers
  hosts: dbservers
  become: yes
  roles:
    - mysql
    - firewall

8. Running Ansible in Production

When deploying to production, these options help you work safely and efficiently.

Limit: Target Specific Servers

# Run only on web1
ansible-playbook -i inventory.yml site.yml --limit web1

# Run only on webservers group
ansible-playbook -i inventory.yml site.yml --limit webservers

# Exclude a specific server
ansible-playbook -i inventory.yml site.yml --limit 'all:!db1'

Tags: Run Only Specific Tasks

# Tag tasks in your Playbook
    - name: Install Nginx
      apt:
        name: nginx
      tags: [nginx, install]

    - name: Configure UFW
      ufw:
        rule: allow
        port: '80'
      tags: [firewall, ufw]
# Run only tasks tagged 'nginx'
ansible-playbook -i inventory.yml site.yml --tags nginx

# Skip tasks tagged 'firewall'
ansible-playbook -i inventory.yml site.yml --skip-tags firewall

Tune Parallel Execution with Forks

# Default forks=5 (runs 5 hosts concurrently)
# Increase to 20 hosts at once
ansible-playbook -i inventory.yml site.yml -f 20

# Or configure in ansible.cfg
[defaults]
forks = 20

9. Best Practices for Production

Following these best practices keeps your Ansible setup maintainable and secure in production.

Use Vault for Secrets

# Encrypt sensitive data with Ansible Vault
ansible-vault encrypt_string 'my_db_password' --name 'db_password'

# Create an encrypted vars file
ansible-vault create group_vars/all/vault.yml

# Run Playbook with vault password
ansible-playbook site.yml --ask-vault-pass
# or
ansible-playbook site.yml --vault-password-file ~/.vault_pass

Recommended Directory Structure

ansible-project/
  inventory/
    production/
      hosts.yml
      group_vars/
        webservers.yml
    staging/
      hosts.yml
  roles/
    nginx/
    mysql/
    app/
  playbooks/
    site.yml
    deploy.yml
    maintenance.yml
  ansible.cfg
✅ Production Checklist:

1. Always run --check first | 2. Store Playbooks in Git | 3. Use --limit to test on one server first | 4. Use Vault for all passwords | 5. Set ANSIBLE_NOCOWS=1 in CI/CD pipelines

10. Frequently Asked Questions

What is the difference between Ansible and Terraform?

Ansible focuses on Configuration Management — configuring the OS, installing software, and deploying applications. Terraform focuses on Infrastructure Provisioning — creating and managing cloud resources like VMs, networks, and storage. They complement each other well: Terraform provisions the VPS, Ansible configures it.

Do I need to install an agent on each VPS?

No. Ansible is completely agentless — it communicates over SSH directly. No special software is required on managed VPS instances. Python 3 (included in all Ubuntu versions) is sufficient.

Can Ansible manage Windows servers?

Yes. Ansible supports Windows Server via WinRM (Windows Remote Management) instead of SSH, with additional configuration. For Linux/Ubuntu VPS, Ansible connects via SSH with no extra setup.

Can Ansible scale to hundreds of VPS servers?

Yes. Ansible scales well using --forks to increase parallel execution (default: 5, can be raised to 50+). For very large deployments, Ansible Tower or AWX adds a Web UI, role-based access control, and job scheduling.

What's the difference between Ansible Tower and AWX?

AWX is the open-source, free version of Ansible Tower but without official support. Ansible Tower (now Red Hat Ansible Automation Platform) is the commercial version with support, SLA guarantees, and additional enterprise features.

What's the difference between a Playbook and an ad-hoc command?

Ad-hoc commands are for quick one-off tasks like rebooting a server or checking disk space. Playbooks are YAML files that define reusable workflows, can be version-controlled in Git, and are designed to be shared and repeated across your team.

Conclusion

Ansible transforms VPS management from repetitive manual work into a reliable, automated process. Start with a small Inventory and simple Playbooks, then progressively organize your work using Roles as your infrastructure grows.

The most important habit: always test with --check first, and store every Playbook in Git so your team can collaborate and roll back when needed.

Need a VPS Ready for Ansible?

AsiaGB offers Ubuntu VPS with full SSH access, 99% Uptime SLA, and SSD storage — perfect for Ansible automation.

View VPS Plans

Part of the AsiaGB Article Library · อ่านภาษาไทย · 中文版本