Running a Real, Offline Terraform Engine Inside a Shell-less Distroless Container on Scale-to-Zero Cloud Run
Cloud Architecture · 9 min
How to embed a PGP-verified Terraform binary, pre-seeded provider filesystem mirror, and Terraform 1.7 mock_provider inside a Debian 13 distroless Cloud Run image with zero cloud credentials or outbound network calls.
Most interactive infrastructure demos on portfolio sites fake their output with setTimeout and pre-recorded strings. When I built the Terraform GCP Madrid showcase for this site (ADR-001, ADR-022, ADR-032), I wanted visitors to run the genuine HashiCorp Terraform binary against live configuration changes while maintaining three non-negotiable production constraints:
- True scale-to-zero economics on Google Cloud Run (
min_instance_count = 0) with sub-second cold starts. - A shell-less
gcr.io/distroless/nodejs26-debian13:nonrootruntime with no/bin/sh, no package manager, and no ambient GCP credentials. - Zero remote API calls or arbitrary code execution—even though the endpoint is publicly callable by anonymous visitors.
Here is how the architecture works end-to-end.
1. Never Accept Raw HCL from the Client
Allowing an anonymous HTTP caller to submit raw HCL to terraform plan is a remote code execution vulnerability waiting to happen (external data sources, local-exec provisioners, or arbitrary provider downloads). Instead, the browser sends a strictly typed JSON payload validated by Zod, and the server deterministically synthesizes the HCL from a shared generator (src/data/terraformHcl.ts):
export const TerraformSchema = z.object({
selectedModule: z.enum(['cloud_run', 'vpc_network', 'cloud_sql', 'github_oidc']),
projectId: z.string().regex(/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/),
gcpRegion: z.enum(['europe-southwest1', 'europe-west1', 'us-east1', 'asia-east1']),
scaleToZero: z.boolean(),
multiZone: z.boolean(),
});
Because the generated HCL is create-only and contains zero data blocks, terraform plan -refresh=false never needs to query live GCP state.
2. Baking a PGP-Verified Terraform Binary and Provider Mirror into Distroless
In a scale-to-zero container, running terraform init against registry.terraform.io on every request would add ~180 MB of network egress and 8–12 seconds of latency. Worse, if the registry hiccups, the demo breaks.
In my multi-stage Dockerfile, a dedicated terraform stage imports HashiCorp's PGP key, verifies the SHA256SUMS.sig signature of the Terraform binary against the pinned fingerprint, downloads the pinned hashicorp/google provider once at image build time into a local filesystem_mirror, and pre-initializes a working directory:
FROM debian:13-slim AS terraform
ARG TERRAFORM_VERSION=1.17.2
ARG TF_GOOGLE_PROVIDER_VERSION=8.12.0
COPY scripts/hashicorp.asc /tmp/hashicorp.asc
RUN gpg --batch --import /tmp/hashicorp.asc && \
curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_${TF_ARCH}.zip" && \
curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_SHA256SUMS" && \
curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_SHA256SUMS.sig" && \
gpg --batch --verify "terraform_${TERRAFORM_VERSION}_SHA256SUMS.sig" "terraform_${TERRAFORM_VERSION}_SHA256SUMS" && \
grep " terraform_${TERRAFORM_VERSION}_linux_${TF_ARCH}.zip$" "terraform_${TERRAFORM_VERSION}_SHA256SUMS" | sha256sum -c -
I also ship a static /tf.terraformrc that disables direct network access for provider installation:
provider_installation {
filesystem_mirror {
path = "/app/tf-mirror"
include = ["registry.terraform.io/hashicorp/google"]
}
direct {
exclude = ["registry.terraform.io/hashicorp/google"]
}
}
On each request, server/terraform.ts creates a fresh /tmp/tf-demo-* workspace and runs terraform init -backend=false against the local provider mirror in milliseconds with zero network I/O.
3. Running `apply` Offline with Terraform 1.7's `mock_provider`
How do you let a visitor run terraform apply without provisioning real Cloud Run services or Cloud SQL databases? Terraform 1.7 introduced terraform test with first-class mock_provider blocks. I generate a main.tftest.hcl file alongside main.tf:
mock_provider "google" {
mock_resource "google_cloud_run_v2_service" {
defaults = {
uri = "https://charlie-portfolio-app-mock-europe-southwest1.a.run.app"
}
}
}
run "apply_madrid_stack" {
command = apply
}
```
When the visitor clicks Terraform Apply, the server invokes terraform test -no-color. The real Terraform core builds the dependency DAG, evaluates expressions, synthesizes computed attributes using mock_provider, and streams every line over Server-Sent Events (SSE).
4. Subprocess Hardening in a Shell-less Runtime
Because gcr.io/distroless/nodejs26-debian13:nonroot has no /bin/sh, spawn(TERRAFORM_BIN, args, { cwd, env }) must use the direct argv vector form (shell: false). I also pass a strict environment allowlist so Secret Manager values in the Node process (RESEND_API_KEY, TURNSTILE_SECRET_KEY, CV_GATE_SECRET) are never inherited by the Terraform child process or provider plugin:
const TERRAFORM_ENV_ALLOWLIST = [
'PATH', 'HOME', 'TMPDIR', 'LANG', 'TF_CLI_CONFIG_FILE', 'TF_PLUGIN_CACHE_DIR'
] as const;
export function terraformChildEnv(source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {};
for (const key of TERRAFORM_ENV_ALLOWLIST) {
if (source[key] !== undefined) env[key] = source[key];
}
return {
...env,
TF_IN_AUTOMATION: '1',
CHECKPOINT_DISABLE: '1',
// Satisfies the google provider's eager credential check during plan -refresh=false
// without ever touching the network or metadata server:
GOOGLE_OAUTH_ACCESS_TOKEN: 'offline-demo-no-network-call',
};
}
```
If the visitor closes the browser tab mid-run, the Express response close listener fires an AbortSignal that immediately sends SIGKILL to the child process and cleans up the /tmp workspace.