Use Terraform to automatically initialize your VPS infrastructure (Infrastructure as Code)
Using Terraform for Automated VPS Infrastructure (Infrastructure as Code)
In the DevOps era of 2026, logging into web interfaces of providers like DigitalOcean, Vultr, or AWS to manually click and create servers is obsolete. This method is not only time-consuming but also prone to configuration errors between environments (Dev, Staging, Production). Infrastructure as Code (IaC), with a focus on Terraform, was born to solve this: transforming infrastructure into manageable, shareable, and reusable source code.
This article dives deep into using Terraform to define entire system resources—from VPS and Firewalls to Networks—through a single configuration file. With just one command, you can deploy dozens of servers in minutes.
1. What is Terraform and Why Should Developers Care?
Terraform is an open-source tool developed by HashiCorp that uses a declarative language called HCL (HashiCorp Configuration Language). Instead of writing step-by-step scripts (Imperative), you simply describe the desired end state (Declarative).
- Consistency: Ensures the Production environment is identical to Staging.
- Version Control: You can store infrastructure on Git and use Pull Requests to review server configuration changes.
- Multi-provider: Use the same logic to manage DigitalOcean, Google Cloud, or even on-premise Proxmox.
// Example logic to check infrastructure state in a Terraform management system
interface InfrastructureState {
resourcesCreated: number;
provider: string;
isProvisioned: boolean;
}
function checkDeploymentProgress(state: InfrastructureState): string {
if (state.isProvisioned) {
return `Infrastructure on ${state.provider} is ready with ${state.resourcesCreated} resources.`;
}
return "Initialization or update in progress...";
}
const myProjectState: InfrastructureState = {
resourcesCreated: 5,
provider: "DigitalOcean",
isProvisioned: true
};
console.log(checkDeploymentProgress(myProjectState));
2. Core Structure of a Terraform Project
To start automating your VPS, you need to understand three main components: Provider, Resource, and Variables. Terraform uses these components to build a "resource graph" and determine the most optimal creation order.
For example, a Firewall must be created before being applied to a VPS, and a Network must exist before assigning an IP to a server. Terraform calculates these dependencies automatically so you don't have to.
// Sample Resource declaration structure in Terraform HCL (Mocked as TypeScript interface)
interface TerraformResource {
type: string;
name: string;
properties: {
region: string;
size: string;
image: string;
ssh_keys?: string[];
};
}
const webServer: TerraformResource = {
type: "digitalocean_droplet",
name: "web-vps-01",
properties: {
region: "sgp1", // Singapore
size: "s-1vcpu-2gb",
image: "ubuntu-22-04-x64",
ssh_keys: ["id_rsa_my_mac"]
}
};
console.log(`Defining resource: ${webServer.type}.${webServer.name}`);
3. The 4-Step Automated Deployment Process
When working with Terraform, you will always follow a closed cycle that minimizes the risk of crashing a live system.
| Command | Purpose | System Action |
|---|---|---|
| terraform init | Project Initialization | Downloads provider plugins (DigitalOcean, AWS, etc.) |
| terraform plan | Planning | Compares code against reality and lists expected changes |
| terraform apply | Execution | Sends API requests to the provider to create/modify resources |
| terraform destroy | Cleanup | Wipes the entire created infrastructure to save costs |
4. Variables and Reusability
Never "hard-code" parameters like IPs or RAM capacity into the main file. Use variables.tf to make your configuration flexible. This allows you to use the same codebase to create a Small VPS for Dev and a High-end VPS for Production.
// Logic for handling variables in an infrastructure management system
type VpsSize = "1gb" | "2gb" | "4gb" | "8gb";
interface DeploymentConfig {
environment: "dev" | "prod";
vpsSize: VpsSize;
}
function getPriceEstimation(config: DeploymentConfig): number {
const pricing = { "1gb": 5, "2gb": 10, "4gb": 20, "8gb": 40 };
const multiplier = config.environment === "prod" ? 1.5 : 1; // Prod includes backup fees
return pricing[config.vpsSize] * multiplier;
}
const myDeploy: DeploymentConfig = { environment: "prod", vpsSize: "4gb" };
console.log(`Estimated monthly cost: $${getPriceEstimation(myDeploy)}`);
5. Automating Firewalls and Network Security
One of the biggest mistakes is forgetting to configure the firewall after creating a VPS. With Terraform, the Firewall is part of the "blueprint." You define which ports are open (80, 443, 22) directly in the code. When the VPS is created, it is protected from the very first second.
// Defining a list of allowed ports (Firewall Rules)
interface FirewallRule {
protocol: "tcp" | "udp" | "icmp";
portRange: string;
sourceAddresses: string[];
}
const securityPolicy: FirewallRule[] = [
{ protocol: "tcp", portRange: "80", sourceAddresses: ["0.0.0.0/0"] },
{ protocol: "tcp", portRange: "443", sourceAddresses: ["0.0.0.0/0"] },
{ protocol: "tcp", portRange: "22", sourceAddresses: ["123.45.67.89/32"] } // Your IP only
];
console.log(`Applying ${securityPolicy.length} security rules to the infrastructure.`);
6. State Management with the State File (.tfstate)
Terraform remembers what it created via a file called terraform.tfstate. This file is extremely critical. If you lose it, Terraform won't know which servers are running and will attempt to recreate everything, leading to duplicates or errors. In enterprise environments, this file is stored on the Cloud (S3, Terraform Cloud) for team collaboration.
7. Combining Terraform with Cloud-Init for Software Installation
Creating an empty VPS isn't enough. You need Nginx, Docker, or Node.js ready the moment the server turns on. Terraform allows you to embed User Data (Cloud-Init) scripts. Once the server finishes hardware initialization, it automatically runs this script to set up the environment.
// Mock Cloud-Init script for Docker environment setup
const cloudInitScript = `
#!/bin/bash
apt-get update
apt-get install -y docker.io
systemctl start docker
docker run -d -p 80:80 nginx
`;
function getProvisioningScript(os: string): string {
console.log(`Assigning post-initialization script for OS: ${os}`);
return cloudInitScript;
}
getProvisioningScript("Ubuntu 22.04");
8. Conclusion: The IaC Transition Checklist
Before officially using Terraform for your next project, ensure you have completed the following steps:
- Installed Terraform CLI and configured your provider's API Token?
- Separated variables files from the main execution logic?
- Created a plan for secure
.tfstatestorage (Remote Backends)? - Double-checked the
terraform planoutput to avoid accidental deletion of Production data?
Terraform is not just a tool; it is a new mindset for system management. Start automating today to free yourself from repetitive manual tasks!
