Manage Cloud with Terraform

Manage your Cloud servers, firewalls and SSH keys as code with the Better Stack Terraform provider, BetterStackHQ/betterstack.

Get an API token

Create a global API token in Settings → API tokens → Global tokens, and set it as the BETTERSTACK_API_TOKEN environment variable in the shell that runs Terraform.

Configure the provider

Each data center is managed separately, so set the one your resources are in as availability_zone:

main.tf
terraform {
  required_providers {
    betterstack = {
      source  = "BetterStackHQ/betterstack"
      version = "~> 1.5"
    }
  }
}

provider "betterstack" {
  availability_zone = "us-west-2a"
}

Create your first server

Add your SSH key, a firewall that lets in SSH and HTTPS, and a server that uses both. Replace t123 with your team's ID from betterstack team list in the Cloud CLI:

main.tf
resource "betterstack_ssh_key" "laptop" {
  team_id    = "t123"
  slug       = "my-laptop"
  public_key = file("~/.ssh/id_ed25519.pub")
}

resource "betterstack_firewall" "web" {
  team_id = "t123"
  name    = "web"
}

resource "betterstack_firewall_rule" "ssh" {
  firewall_id  = betterstack_firewall.web.id
  direction    = "inbound"
  protocol     = "tcp"
  ip_addresses = ["0.0.0.0/0", "::/0"]
  port_from    = 22
}

resource "betterstack_firewall_rule" "https" {
  firewall_id  = betterstack_firewall.web.id
  direction    = "inbound"
  protocol     = "tcp"
  ip_addresses = ["0.0.0.0/0", "::/0"]
  port_from    = 443
}

resource "betterstack_server" "web" {
  team_id      = "t123"
  name         = "web-1"
  server_type  = "AM1"
  image        = "ubuntu-26-04"
  ssh_keys     = [betterstack_ssh_key.laptop.slug]
  firewall_ids = [betterstack_firewall.web.id]
}

output "server_ip" {
  value = [for a in betterstack_server.web.ip_addresses : a.ip if a.type == "ipv4"][0]
}
Create the server
terraform init
terraform apply

Connect as root:

Connect to the server
ssh root@$(terraform output -raw server_ip)

A firewall created this way has no inbound rules of its own, so keep the SSH rule to reach the server.

Removing a server?

Servers start with deletion_protection = true. To remove one with terraform destroy, set deletion_protection = false and run terraform apply first.

Import existing resources

Bring a server you created in the dashboard or the CLI under Terraform with an import block. Find its ID in the ID column:

List your servers
betterstack server list --availability-zone us-west-2a
import.tf
import {
  to = betterstack_server.imported
  id = "51374dd8-1b10-419c-974d-a30eb461e2f1"
}

Write its configuration, then apply:

Import the server
terraform plan -generate-config-out=imported.tf
terraform apply

Need help?

Please let us know at hello@betterstack.com.
We're happy to help! 🙏