+++
title = "Define Cloudflare Workers script resource — WASM artifact, D1 binding, environment variables"
priority = 7
status = "done"
ticket_type = "task"
dependencies = ["2d1371", "d0da0b", "07cafb", "efee79"]
+++
Infrastructure is managed with OpenTofu using the Cloudflare provider.
Trages resolved:
- 07cafb: D1 binding — use `cloudflare_d1_database.db.id` directly; OpenTofu dependency graph handles ordering. No two-phase apply or data source needed.
- efee79: Correct resource name — `cloudflare_workers_script` (plural, confirmed from provider v4 source).
Define the Cloudflare Workers script resource in `infra/worker.tf`.
Every block must have a comment.
```hcl
# infra/worker.tf
# Cloudflare Workers script for the quotesdb API.
# Compiled from the `api` binary targeting wasm32-unknown-unknown.
# The Wasm artifact must be built before running `tofu apply`:
# cargo build --release --target wasm32-unknown-unknown --bin api
resource "cloudflare_workers_script" "api" {
account_id = var.cloudflare_account_id
# Script name used in Cloudflare dashboard and for routing.
name = "quotesdb-api"
# Compiled Wasm binary content, base64-encoded.
# Path is relative to the infra/ directory.
content = filebase64("../target/wasm32-unknown-unknown/release/api.wasm")
# D1 database binding — referenced in workers-rs code as `env.DB`.
# `database_id` is resolved at apply time from the D1 resource output.
# OpenTofu automatically creates the D1 database before this script
# because of the attribute reference below (no explicit depends_on needed).
d1_database_binding {
name = "DB"
database_id = cloudflare_d1_database.db.id
}
# Workers runtime compatibility date.
compatibility_date = "2024-09-23"
}
```
- The `content` attribute expects base64-encoded script bytes. For a Wasm Worker, this is the raw compiled Wasm file, not a JS bundle.
- The binding `name = "DB"` must match exactly what the workers-rs API code uses (`env.DB`). Verify this in `src/bin/api/main.rs`.
- `(known after apply)` for `database_id` in `tofu plan` is expected and correct — OpenTofu resolves it at apply time.
- The Wasm binary must be compiled before `tofu apply`. This is handled by the Gitea Actions CI/CD workflow (ticket to be created; also see ticket 5137d7 for the UI workflow pattern).
Run from the `infra/` directory:
```sh
tofu validate
tofu plan
```
`feat(quotesdb): define Cloudflare Workers script resource in OpenTofu`