Ansible Practical: Multi-Server Deployment
Moving beyond local testing, professional DevOps engineers use Ansible to manage clusters of servers simultaneously. In this guide, you will orchestrate a deployment across three separate target servers, based on the sixty-fourth image.
🏗️ Phase 1: Architecture & Inventory
1. The Strategy
We will use:
- 1 Control Node: (The machine where Ansible is installed).
- 3 Managed Nodes: Fresh Ubuntu instances (Target Servers).
2. The Inventory File (host)
Create a file named host (no extension) and add the public IP addresses of your three managed nodes:
[webservers]
13.127.151.10
3.110.163.221
65.0.30.222📂 Phase 2: Project Orchestration
1. Ansible Configuration (ansible.cfg)
Create an ansible.cfg file in your project directory to simplify your commands:
[defaults]
inventory = host
remote_user = ubuntu
private_key_file = ./your-key.pem
host_key_checking = False2. Variable Management (vars/default.yml)
Create a folder named vars/ and a file inside called default.yml. This keeps your playbook clean and modular.
---
package_name: nginx
title: "Welcome to My Automated Cluster"
content: "This page was deployed automatically by Ansible to multiple servers!"📄 Phase 3: The Templating Engine
Jinja2 Template (templates/index.html.j2)
Create a folder named templates/ and a file inside called index.html.j2. We use .j2 because it's a Jinja2 template.
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
<p>Server: {{ ansible_hostname }}</p>
</body>
</html>🚀 Phase 4: The Playbook (setup-nginx.yml)
Create your main playbook to orchestrate the entire deployment:
---
- name: Deploy Web Cluster
hosts: webservers
become: yes
vars_files:
- vars/default.yml
tasks:
- name: 1. Install Nginx
apt:
name: "{{ package_name }}"
state: latest
update_cache: yes
- name: 2. Deploy Index Page from Template
template:
src: templates/index.html.j2
dest: /var/www/html/index.html
- name: 3. Restart Nginx
service:
name: "{{ package_name }}"
state: restarted🏁 Phase 5: Scalable Execution
Run the playbook and watch as Ansible manages all three servers in parallel:
ansible-playbook setup-nginx.ymlVerification
Open your browser and visit the Public IP of all three servers. You should see the exact same personalized page, but with a different Server Name displayed at the bottom (thanks to the ansible_hostname variable).
[!TIP] Why use Templates? Templates allow you to deploy files that are almost identical across servers, but contain small unique pieces of data (like IP addresses, hostnames, or specific IDs). Ansible's Jinja2 engine handles the replacement logic automatically.