Use deletion_protected on the planetscale_neki_branch resource and verify the server-side block with a TypeScript probe.
What you will build
A Terraform-managed Neki branch with server-side deletion protection, plus a TypeScript probe that confirms the API rejects deletion attempts.
Import existing Neki branch -> set deletion_protected = true -> terraform apply -> terraform destroy blocked -> TypeScript probe confirms deletion_protected remains true
AI prompt
Show how to stop Terraform from accidentally destroying a production Neki branch. Use the PlanetScale Terraform provider's deletion_protected attribute, import an existing branch, apply the protection, and verify that both terraform destroy and a direct API delete are rejected.
Prerequisites
- Terraform CLI 1.5 or later
- Node.js 22+ with npm
- A PlanetScale service token with database read/write access
- An existing Neki database and branch created in PlanetScale
Resource arguments used below are documented in the PlanetScale provider's planetscale_neki_branch reference; the server-side block is described in the deletion-protection guide.
Environment variables
PLANETSCALE_SERVICE_TOKEN(secret): PlanetScale service token used by the Terraform provider and the API probePLANETSCALE_ORG: PlanetScale organization slugPLANETSCALE_DATABASE: Neki database namePLANETSCALE_BRANCH: Neki branch name to protect, typically main
1. Create the Terraform configuration
Create neki-branch.tf to configure the PlanetScale provider and import the existing Neki branch. The deletion_protected argument is the server-side guard that stops Terraform (and the API) from deleting the branch.
terraform {
required_providers {
planetscale = {
source = "planetscale/planetscale"
version = "~> 1.18.0"
}
}
}
provider "planetscale" {
service_token = var.planetscale_service_token
}
import {
to = planetscale_neki_branch.production
id = jsonencode({
organization = var.planetscale_organization
database = var.planetscale_database
id = var.planetscale_branch_id
})
}
resource "planetscale_neki_branch" "production" {
organization = var.planetscale_organization
database = var.planetscale_database
name = var.planetscale_branch
deletion_protected = true
}
2. Declare variables and values
Create variables.tf for the provider inputs and terraform.tfvars with your organization, database, branch, and branch ID. The branch ID is the PlanetScale API id field for the branch, not the branch name.
# variables.tf
variable "planetscale_service_token" {
description = "PlanetScale service token"
type = string
sensitive = true
}
variable "planetscale_organization" {
description = "PlanetScale organization slug"
type = string
}
variable "planetscale_database" {
description = "Neki database name"
type = string
}
variable "planetscale_branch" {
description = "Neki branch name"
type = string
}
variable "planetscale_branch_id" {
description = "Neki branch ID from the PlanetScale API"
type = string
}
# terraform.tfvars
planetscale_organization = "your-org"
planetscale_database = "your-neki-database"
planetscale_branch = "main"
planetscale_branch_id = "your-branch-id"
3. Initialize and apply Terraform
Run terraform init and apply. Terraform imports the existing branch into state and then updates deletion_protected from false to true. Pass the service token as a variable so it is never written to disk.
terraform init -input=false
terraform apply -input=false -auto-approve \
-var="planetscale_service_token=$PLANETSCALE_SERVICE_TOKEN"
4. Add the TypeScript verification probe
Create verify.ts to read the branch state from the PlanetScale API and attempt a delete. The probe fails unless the API reports deletion_protected is true and rejects the delete with code deletion_protected.
import process from "node:process";
interface Branch {
id: string;
name: string;
deletion_protected: boolean;
state: string;
production: boolean;
}
async function api<T>(path: string, init?: RequestInit): Promise<T> {
const token = process.env.PLANETSCALE_SERVICE_TOKEN;
if (!token) throw new Error("Missing PLANETSCALE_SERVICE_TOKEN");
const base = "https://api.planetscale.com/v1";
const res = await fetch(`${base}${path}`, {
...init,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
...init?.headers,
},
});
const body = await res.json().catch(() => ({}));
return body as T;
}
async function runVerification() {
const org = process.env.PLANETSCALE_ORG;
const database = process.env.PLANETSCALE_DATABASE;
const branch = process.env.PLANETSCALE_BRANCH;
if (!org || !database || !branch) {
throw new Error("Set PLANETSCALE_ORG, PLANETSCALE_DATABASE, and PLANETSCALE_BRANCH");
}
console.log(`Verifying ${org}/${database}/${branch}...`);
const getPath = `/organizations/${org}/databases/${database}/branches/${branch}`;
const branchState = await api<Branch>(getPath);
console.log("Branch state:", {
id: branchState.id,
name: branchState.name,
deletion_protected: branchState.deletion_protected,
state: branchState.state,
production: branchState.production,
});
if (!branchState.deletion_protected) {
throw new Error("deletion_protected is false; Terraform did not protect the branch");
}
console.log("Attempting API delete to confirm server-side enforcement...");
const deleteResult = await api<Record<string, unknown>>(getPath, { method: "DELETE" });
console.log("Delete response:", JSON.stringify(deleteResult));
const isProtected =
("code" in deleteResult && deleteResult.code === "deletion_protected") ||
("message" in deleteResult &&
typeof deleteResult.message === "string" &&
deleteResult.message.includes("protected"));
if (!isProtected) {
throw new Error("Expected deletion_protected error, got different response");
}
console.log("Confirmed: branch is protected from deletion.");
}
runVerification().catch((err) => {
console.error(err);
process.exit(1);
});
5. Run the end-to-end verification
Install the TypeScript runner and run the full chain. The command applies deletion protection, attempts a Terraform destroy, and then uses the probe to confirm the branch is still protected. The destroy step is expected to fail and is wrapped so the chain continues.
npm install
terraform init -input=false && \
terraform apply -input=false -auto-approve \
-var="planetscale_service_token=$PLANETSCALE_SERVICE_TOKEN" && \
{ terraform destroy -input=false -auto-approve \
-var="planetscale_service_token=$PLANETSCALE_SERVICE_TOKEN" || true; } && \
npx tsx verify.ts
Verify the result
Run against planetscale/planetscale v1.18.0 on 2026-11-05.
terraform init -input=false && terraform apply -input=false -auto-approve -var="planetscale_service_token=$PLANETSCALE_SERVICE_TOKEN" && { terraform destroy -input=false -auto-approve -var="planetscale_service_token=$PLANETSCALE_SERVICE_TOKEN" || true; } && npx tsx verify.ts
Observed output:
$ terraform apply -input=false -auto-approve -var="planetscale_service_token=$PLANETSCALE_SERVICE_TOKEN"
planetscale_neki_branch.production: Importing... [id={"database":"neki-terraform-protect-1793849409","id":"z1amr0qbez2o","organization":"[REDACTED]"}]
planetscale_neki_branch.production: Import complete [id={"database":"neki-terraform-protect-1793849409","id":"z1amr0qbez2o","organization":"[REDACTED]"}]
planetscale_neki_branch.production: Modifying... [id=z1amr0qbez2o]
planetscale_neki_branch.production: Modifications complete after 1s [id=z1amr0qbez2o]
Apply complete! Resources: 1 imported, 0 added, 1 changed, 0 destroyed.
$ terraform destroy -input=false -auto-approve -var="planetscale_service_token=$PLANETSCALE_SERVICE_TOKEN"
planetscale_neki_branch.production: Destroying... [id=z1amr0qbez2o]
╷
│ Error: failure to invoke API
│
│ PlanetScale API returned HTTP 422 (deletion_protected): This branch is
│ protected from deletion.
╵
$ npx tsx verify.ts
Verifying [REDACTED]/neki-terraform-protect-1793849409/[REDACTED]...
Branch state: {
id: 'z1amr0qbez2o',
name: '[REDACTED]',
deletion_protected: true,
state: 'ready',
production: true
}
Attempting API delete to confirm server-side enforcement...
Delete response: {"code":"deletion_protected","message":"This branch is protected from deletion."}
Confirmed: branch is protected from deletion.
Expected: Terraform imports the branch, enables deletion_protected, rejects terraform destroy with HTTP 422 (deletion_protected), and the TypeScript probe confirms the branch still has deletion_protected set to true.
How it works
The PlanetScale Terraform provider maps the deletion_protected argument to the PlanetScale API's branch deletion protection flag. When the flag is true, the API returns HTTP 422 with code deletion_protected for any delete request, including those issued by terraform destroy. The TypeScript probe reads the branch through the public API and also attempts a delete to surface the same error directly.
What the run corrected
These are beliefs the documentation supported and the run disproved.
- Assumed: Terraform would refuse to plan a destroy when deletion_protected is true. Observed: Terraform still plans and attempts the destroy. The PlanetScale API rejects the request with HTTP 422 and code deletion_protected. Evidence: terraform destroy produced 'PlanetScale API returned HTTP 422 (deletion_protected): This branch is protected from deletion.'
Common issues
terraform destroy fails with an error other than deletion_protected
Cause: The branch was deleted outside Terraform or the resource was never imported. Without an import, Terraform tries to create a new branch instead of managing the existing one.
Fix: Import the existing branch first using the import block with the JSON id object containing organization, database, and branch id.
Neki database creation fails with 'Cluster size is invalid'
Cause: Neki databases require Neki-specific cluster size SKUs, not the standard Vitess/Postgres sizes.
Fix: Query /v1/organizations/{org}/cluster-size-skus?engine=neki and use a SKU such as PS_DEV_AWS_X86_NEKI.
terraform plan wants to replace the branch
Cause: The name, organization, database, or parent_branch argument was changed. These fields force replacement.
Fix: Keep those arguments matching the imported branch. Only change deletion_protected in the first apply.
Next steps
- Add Terraform's lifecycle { prevent_destroy = true } as a client-side guard for resources that must never leave state
- Enable deletion_protected at the database level with the PlanetScale API or provider to block the entire database from deletion
- Require Terraform plan review in CI so deletion_protected changes are visible before apply
verification:
status: verified
tested_at: "2026-11-05"
product_version: "planetscale/planetscale v1.18.0"
command: "terraform init + apply to import the Neki branch and set deletion_protected=true, then attempt terraform destroy, then run a TypeScript probe that reads the branch state and attempts an API DELETE"
expected_result: "apply imports the branch and changes deletion_protected from false to true; destroy fails with 'PlanetScale API returned HTTP 422 (deletion_protected): This branch is protected from deletion.'; probe reports deletion_protected=true and DELETE response {code:'deletion_protected', message:'This branch is protected from deletion.'}"