Terraform allows you to define your LightYear infrastructure as code, enabling version control, repeatable deployments, and automated provisioning.
Prerequisites
- Terraform v1.5+ installed
- A LightYear API key
Step 1 — Configure the Provider
Create a main.tf file:
terraform {
required_providers {
lightyear = {
source = "lightyear/lightyear"
version = "~> 1.0"
}
}
}
provider "lightyear" {
api_key = var.lightyear_api_key
}
variable "lightyear_api_key" {
type = string
sensitive = true
}Create a terraform.tfvars file (add to .gitignore):
lightyear_api_key = "YOUR_API_KEY"Step 2 — Define a Server Resource
data "lightyear_os" "ubuntu_22" {
filter {
name = "name"
values = ["Ubuntu 22.04 LTS"]
}
}
resource "lightyear_server" "web" {
region = "sgp-01"
plan = "vc2-2c-4gb"
os_id = data.lightyear_os.ubuntu_22.id
label = "web-server-tf"
hostname = "web-server-tf"
backups = "enabled"
ssh_key_ids = [lightyear_ssh_key.deployer.id]
tags = ["production", "terraform"]
}
resource "lightyear_ssh_key" "deployer" {
name = "deployer-key"
ssh_key = file("~/.ssh/id_ed25519.pub")
}
output "server_ip" {
value = lightyear_server.web.main_ip
}Step 3 — Initialise and Apply
$terraform initInitializing the backend...
Initializing provider plugins...
- Finding lightyear/lightyear versions matching "~> 1.0"...
- Installing lightyear/lightyear v1.2.0...
Terraform has been successfully initialized!$terraform planPlan: 2 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ server_ip = (known after apply)$terraform applyStep 4 — Define a Load Balancer
resource "lightyear_load_balancer" "web_lb" {
region = "sgp-01"
label = "web-lb-tf"
forwarding_rules {
frontend_protocol = "HTTP"
frontend_port = 80
backend_protocol = "HTTP"
backend_port = 80
}
health_check {
protocol = "HTTP"
port = 80
path = "/health"
check_interval = 15
response_timeout = 5
unhealthy_threshold = 3
healthy_threshold = 2
}
attached_instances = [lightyear_server.web.id]
}Step 5 — Destroy Infrastructure
$terraform destroy[!IMPORTANT]
terraform destroypermanently deletes all managed resources. Always review the plan output before confirming.
Store State Remotely
For team environments, store Terraform state in object storage:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "lightyear/production.tfstate"
region = "sgp-01"
endpoint = "https://sgp-01.objectstorage.lightyear.host"
}
}