Skip to main content
Apidly

Optional cookies only if you accept. Cookie policy

Infrastructure as code for GPU workloads with Terraform and OpenTofu

Describe GPU servers, volumes, templates, serverless endpoints and the budget in Terraform or OpenTofu, with price guards, auto-stop rules and safe replacement.

Published December 3, 20268 min read

Teams that already describe their infrastructure in Terraform or OpenTofu usually want their GPU servers in the same files: reviewed in a pull request, planned before they are applied, and reproducible. GPU servers make this more delicate than most resources, because they cost money every second and a careless change can replace one and wipe its disk. This post shows how the Apidly provider handles that, using the real resource and attribute names.

A note on availability first. The provider is built from source today. It is not yet published to the Terraform Registry or the OpenTofu Registry, so terraform init cannot download it by itself. The next section shows how to build and use it locally, which is also how its own tests drive the real Terraform and OpenTofu binaries. If you would rather not build anything, the infrastructure as code guide describes the same idea with the command-line tool, using an apidly.yaml file and apidly plan and apidly apply. Pick one tool per server: two tools managing the same server will undo each other.

Build the provider and point Terraform at it

You need Go 1.25.8 or newer (the version in the provider's go.mod). From the repository's provider folder:

cd packages/terraform-provider
go build -o bin/terraform-provider-apidly .

Then tell Terraform where the binary is with a CLI configuration file kept outside your repository. The address is the one built into the provider, apidly.com/apidly/apidly:

# dev.tfrc
provider_installation {
  dev_overrides {
    "apidly.com/apidly/apidly" = "/absolute/path/to/packages/terraform-provider/bin"
  }
  direct {}
}
export TF_CLI_CONFIG_FILE=/absolute/path/to/dev.tfrc
export APIDLY_API_KEY=...        # same variable as the CLI and the SDKs

With an override you do not run terraform init for this provider. Terraform prints a warning that development overrides are in effect; that is expected. terraform validate checks your configuration against the provider's schema and makes no API call, so it works without a key. plan and apply call the API, and apply creates real, billed resources. The provider's tests run against an in-process stub of the API and refuse any host that is not on the loopback address, so running them costs nothing.

A first configuration

terraform {
  required_providers {
    apidly = {
      source = "apidly.com/apidly/apidly"
    }
  }
}

provider "apidly" {}

data "apidly_template" "pytorch" {
  id = "pytorch"
}

data "apidly_plans" "cheap_24gb" {
  min_vram_gb  = 24
  availability = "available"
  sort         = "price"
}

resource "apidly_ssh_key" "laptop" {
  name       = "laptop"
  public_key = file("~/.ssh/id_ed25519.pub")
}

resource "apidly_server" "notebook" {
  label       = "notebook"
  plan_id     = data.apidly_plans.cheap_24gb.plans[0].id
  template_id = data.apidly_template.pytorch.id
  disk_gb     = 80
  ssh_key_ids = [apidly_ssh_key.laptop.id]

  max_hourly_usd = "1.00"

  automation = {
    max_runtime_hours = 4
  }

  lifecycle {
    ignore_changes = [plan_id]
  }
}

The data sources read the catalogue: apidly_plans filters and sorts like the price list (min_vram_gb, max_price_usd, region, availability, sort and more), and apidly_template looks up one template by id or slug. terraform plan shows what would be created and the hourly price of the new server; terraform apply creates it and waits until it is running.

Three attributes on apidly_server carry most of the cost safety:

  • max_hourly_usd is a guard. If the plan's price per running hour, disk included, is higher, planning and creating fail and nothing is sent.
  • automation holds automatic stop rules: max_runtime_hours, spend_cap_cents, stop_at, destroy_at, an idle block with threshold_pct and minutes, and a weekly schedule. Only the rules you write are managed; Terraform never touches the others.
  • ignore_changes = [plan_id] keeps the server on the plan it was created with. Prices and stock move, and without this a cheaper plan appearing in the data source would plan a replacement of a running server.

See the price in the plan

apidly_server_quote is a data source that asks the API what a server request would cost per hour today and whether anything would refuse it. It creates, charges and records nothing.

data "apidly_server_quote" "notebook" {
  plan_id     = data.apidly_plans.cheap_24gb.plans[0].id
  template_id = data.apidly_template.pytorch.id
  disk_gb     = 80
}

output "notebook_price_per_hour" {
  value = data.apidly_server_quote.notebook.total_hourly_usd
}

total_hourly_usd is compute plus disk per running hour, and storage_hourly_usd is the disk alone, which is charged while the server exists, also when it is stopped. blockers lists anything that would refuse a real request today, such as insufficient_balance, and launchable is true when that list is empty. Use them in a precondition so a plan fails before anything is sent:

lifecycle {
  precondition {
    condition     = data.apidly_server_quote.notebook.launchable && tonumber(data.apidly_server_quote.notebook.total_hourly_usd) <= 1
    error_message = "Over budget or blocked: ${jsonencode(data.apidly_server_quote.notebook.blockers)}"
  }
}

The quote is read again on every terraform plan, because prices move. In CI this turns "the plan is cheap enough and would be accepted" into a check that fails the pipeline.

Replacement is the dangerous part

Some changes are made in place and some replace the server. For a GPU server the difference is a new, empty disk.

  • In place: label, note, tags, automation, auto_extend, keep_on_start_error and power_state.
  • Replaced: plan_id, template_id, disk_gb, ssh_key_ids, env, the volume, constraints, and also pricing, fallback_plan_ids, variable_set_ids, allow_self_stop and web_terminal.

The plan marks replacements with forces replacement. Read the plan for must be replaced before every apply, and use terraform plan -out=tfplan followed by terraform apply tfplan so you apply exactly what you read. For a server whose disk holds work you have not copied elsewhere, add prevent_destroy = true in lifecycle, which makes Terraform refuse any plan that would destroy it. Volumes have deletion_protection on by default; you must set it to false and apply before a destroy can delete one.

Hardware needs go in a constraints block (region, min_ram_gb, cpu_family, min_disk_bandwidth_mbps, min_pcie_bandwidth_gbps, static_ip and others). Apidly places the server only on a machine that meets them. They are create-only, so changing them replaces the server.

Stopping and starting without fighting the automation

A server's power_state is running or stopped. If you leave it out, Terraform never starts or stops the server, which is what you want when automation stops it by itself: an idle stop stays stopped after the next apply. Set power_state only when you want Terraform to enforce it. automation_rules is read-only and shows every rule in force, including the organization's defaults.

resource "apidly_server" "training" {
  label       = "training"
  plan_id     = data.apidly_plans.cheap_24gb.plans[0].id
  template_id = data.apidly_template.pytorch.id
  disk_gb     = 100

  max_hourly_usd = "0.80"

  automation = {
    max_runtime_hours = 12
    spend_cap_cents   = 2000
    idle = {
      threshold_pct = 5
      minutes       = 30
    }
  }

  lifecycle {
    prevent_destroy = true
  }
}

Here spend_cap_cents = 2000 stops the server once it has cost 20 dollars over its life, max_runtime_hours = 12 stops it after 12 hours of running, and the idle block stops it after 30 minutes under 5% GPU use. A stopped server still pays for its disk until it is destroyed.

Some new servers are reviewed before they start. Nothing is charged while a request waits, and terraform apply waits within the create timeout (60 minutes by default). If the timeout passes first, the request is canceled, so a server you do not know about cannot start later. Raise it with timeouts = { create = "90m" }.

Your own templates, volumes and endpoints

apidly_template describes a template of your organization: image, tag, launch_mode, ports, env, start_script, default_disk_gb, min_vram_gb. Plain env values are visible to your team; put passwords and tokens in secret_env, which is stored encrypted and never returned. Every setting changes in place, and running servers keep the setup they started with.

resource "apidly_volume" "data" {
  name    = "data"
  size_gb = 100
  plan_id = data.apidly_plans.cheap_24gb.plans[0].id
}

A volume lives on one machine, so it is made for the plan you will use with it, and is mounted with volume_id and volume_mount_path on the server. It cannot be resized.

Serverless endpoints are apidly_endpoint. From a model, the platform chooses the template, plan, disk and port, so you leave those out. The cost attributes are the ones from the spend control post:

resource "apidly_endpoint" "chat" {
  model                 = "Qwen/Qwen2.5-7B-Instruct"
  min_workers           = 0
  max_workers           = 2
  max_hourly_spend_usd  = "3"
  monthly_spend_cap_usd = "200"
  resume_at_new_month   = true
  auto_rollback         = true
  rate_limit_per_minute = 300
}

output "openai_base_url" {
  value = apidly_endpoint.chat.openai_base_url
}

max_hourly_spend_usd bounds how many workers run at once, monthly_spend_cap_usd pauses the endpoint at a monthly total, auto_rollback undoes a rolling update whose new workers fail their health check, and rate_limit_per_minute lowers the endpoint's own request limit. One quirk to know: to remove a monthly cap, use the console, the CLI or the API, because a cap that is not in the configuration is kept, not removed.

Put the budget in code too

apidly_budget sets the organization's monthly budget, alert levels and low-balance warning:

resource "apidly_budget" "monthly" {
  monthly_budget_usd = "500"
  alert_thresholds   = [50, 80, 100]
  low_balance_usd    = "25"

  hard_stop         = true
  confirm_hard_stop = true # stops servers when the budget is reached
}

There is one budget per organization, so this resource takes it over: what you leave out is cleared, and a change made in the console shows up in the next plan. hard_stop needs monthly_budget_usd and an explicit confirm_hard_stop = true, the same acknowledgement the CLI asks for, because a hard stop stops running servers. Destroying the resource clears the budget and switches the hard stop off. Needs a key with the full scope.

Keys, secrets and state

Servers need a key with the servers scope; SSH keys, volumes, templates, endpoints and the budget need full. Use a dedicated key for Terraform, with a monthly spending limit, and keep it out of the files: the provider reads APIDLY_API_KEY from the environment.

Variable values are never returned by the API. env on servers and endpoints and secret_env on templates are sensitive, and drift is detected on names only. For standalone secrets, apidly_secret takes value_wo, a write-only value that is sent to the API and never written to the plan or the state; it needs Terraform 1.11 or later, or a current OpenTofu. Raise value_wo_version to send it again. Values you put in plain value fields stay in the state, which is stored in plain text, so protect the state file either way.

Existing resources can be adopted with terraform import, for example terraform import apidly_server.notebook SERVER_ID or terraform import apidly_budget.monthly budget. Imported servers bring their request settings but not variable values, so the first apply takes env as you wrote it. Write the values the server was really started with.

Testing it without spending anything

Two habits make this cheap to adopt. First, run terraform validate in CI: it needs no key and no network. Second, run terraform plan on every pull request with a limited key, and rely on apidly_server_quote preconditions and max_hourly_usd to fail a plan that would be refused or would cost more than you agreed. The apply, which spends money, stays a deliberate step: save the plan with -out and apply that file.

Try what this guide shows

Try it on a real GPU server

Create a free account and add a balance from $10. Servers are billed by the second, and the review step shows the price per hour before you request one.

Related guides