Skip to main content

Terraform provider

The spanway Terraform provider manages what lives inside a running gateway: model deployments, virtual keys, teams and their members, organizations, users, budgets, tags, projects, guardrails, prompts, agents, search tools, access groups, fallbacks, MCP servers, credentials, vector stores and JWT claim mappings. It calls the gateway's management API with a key you supply, so it works against any deployment, whether it came from a Helm chart or a Terraform stack. Its version is the gateway version, built from the same commit and audited against that gateway's OpenAPI schema. Every management endpoint in the schema must be covered by a resource or a data source, or carry a documented allowlist entry, so the provider cannot drift from the API silently.

A real-world scenario​

A platform team keeps every team's budget and model access in Git so changes go through review. They describe the teams, keys and models as Terraform resources, run terraform plan on each pull request, and apply on merge. A budget raised in the Admin UI by hand shows up as drift in the next plan.

Steps​

  1. Declare and configure the provider as shown in Configure it, with SPANWAY_API_BASE and SPANWAY_API_KEY set.

  2. Check that the key is live. The provider sends the key in the x-api-key header, so the check does the same.

    curl "$SPANWAY_API_BASE/key/info" -H "x-api-key: $SPANWAY_API_KEY"

    /key/info answers for any live key, so a 200 proves the key works, not that it may manage the gateway. Resources need the master key or a key owned by a proxy_admin user, and a weaker key passes this check and fails at terraform apply.

  3. Write the resources, for example the model and team in Example, then run terraform init and terraform apply.

  4. In the Admin UI open Models + Endpoints and Teams and check that the new model and team are listed.

  5. Bring objects created by hand under Terraform with terraform import, see Importing existing objects.

Expected result​

terraform apply reports the resources as created, they show in the Admin UI, and a second terraform plan reports no changes.

Install the provider​

The provider is not on the public Terraform Registry yet. Publishing to the registry as spanway/spanway turns on at launch, together with the other public package registries, and until then no release attaches a provider build to its release page. During the private preview, ask your Spanway contact at support@spanway.ai for the provider build that matches your gateway version, check it against the SHA256SUMS file that comes with it, and install it from a local filesystem mirror. Put the unpacked provider under the mirror directory in the layout Terraform expects, for example ~/.terraform.d/plugins/registry.terraform.io/spanway/spanway/2.0.0/linux_amd64/, and point the CLI configuration at that directory:

provider_installation {
filesystem_mirror {
path = "/home/you/.terraform.d/plugins"
include = ["registry.terraform.io/spanway/spanway"]
}
direct {
exclude = ["registry.terraform.io/spanway/spanway"]
}
}

Then declare the provider in required_providers as shown below and run:

terraform init

The same required_providers block keeps working after launch. Remove the provider_installation block then, and terraform init downloads the provider from the registry, where each release carries builds for Linux, macOS, Windows and FreeBSD, a SHA256SUMS file and a detached GPG signature that terraform init checks before it installs the provider. If you would rather not run Terraform before launch, manage the same objects through the Admin UI, the spanwayctl CLI or the Python and TypeScript clients.

Configure it​

terraform {
required_providers {
spanway = {
source = "spanway/spanway"
version = "~> 2.0.0"
}
}
}

provider "spanway" {
api_base = "https://gateway.example.com"
api_key = var.spanway_api_key
}

Pin the provider to the line your gateway runs. Once registry publishing turns on at launch, pre-release versions appear on the registry too, as semantic versions (gateway 2.1.0rc1 is provider 2.1.0-rc.1), and Terraform selects them only when pinned exactly.

ArgumentEnvironment variableWhat it does
api_baseSPANWAY_API_BASERequired. The gateway URL
api_keySPANWAY_API_KEYRequired. A key with the permissions the resources need, usually the master key or a proxy_admin user's key
insecure_skip_verifySPANWAY_INSECURE_SKIP_VERIFYOptional, default false. Skips TLS verification for self-signed development gateways
request_timeout_secondsSPANWAY_REQUEST_TIMEOUT_SECONDSOptional, default 120, from 1 to 3600. How long one call to the gateway may take before the provider gives up. It stops terraform plan or apply from hanging forever when the gateway or a load balancer in front of it stops answering. Raise it only when a slow gateway legitimately needs longer

With the environment variables set, provider "spanway" {} is enough. SPANWAY_INSECURE_SKIP_VERIFY takes true or false, and an insecure_skip_verify argument in the provider block wins over it.

Example​

resource "spanway_model" "sonnet" {
model_name = "claude-sonnet"
custom_llm_provider = "anthropic"
base_model = "claude-sonnet-5-5"
model_api_key = var.anthropic_api_key
mode = "chat"

input_cost_per_million_tokens = 3.0
output_cost_per_million_tokens = 15.0
}

resource "spanway_team" "platform" {
team_alias = "platform"
models = [spanway_model.sonnet.model_name]
max_budget = 500.0
}

resource "spanway_key" "platform_ci" {
key_alias = "platform-ci"
team_id = spanway_team.platform.id
models = [spanway_model.sonnet.model_name]
max_budget = 100.0
budget_duration = "monthly"
rpm_limit = 60
}

spanway_model also takes additional_spanway_params, a map of provider-specific options. String values "true" and "false" become booleans, numeric strings become numbers, strings starting with [ or { are parsed as JSON, and additional_drop_params as a JSON array removes parameters from the final request.

Resources​

ResourceWhat it manages
spanway_modelA model deployment: provider, upstream model, credentials, pricing, mode and extra parameters
spanway_teamA team, its allowed models, budget and limits
spanway_team_memberOne member of a team with a role and a per-member budget
spanway_team_member_addSeveral members added to a team from one resource
spanway_team_blockThe blocked state of an existing team. Creating it blocks every key of the team, destroying it unblocks them
spanway_organizationAn organization and its budget and models. Enterprise
spanway_organization_memberOne member of an organization. Enterprise
spanway_organization_member_addSeveral members added to an organization from one resource. Enterprise
spanway_userAn internal user who can log into the Admin UI, own keys and belong to teams
spanway_keyA virtual key with models, budgets, rate limits, aliases, guardrails, tags and metadata. guardrails needs a license with guardrails, tags needs key_controls and allowed_passthrough_routes needs passthrough_routes
spanway_key_blockThe blocked state of an existing key
spanway_budgetA budget object attachable to keys, teams, organizations and end users
spanway_tagA tag for spend tracking, tag budgets and tag-based routing
spanway_projectA project between a team and its keys, with its own budget and model access
spanway_access_groupA model access group
spanway_unified_access_groupA unified access group that spans models, MCP servers and agents
spanway_guardrailA guardrail with its provider parameters and mode
spanway_promptA prompt template, from an external provider or inline dotprompt content
spanway_agentAn A2A agent registered on the gateway
spanway_search_toolA search tool that connects the /search endpoints to an external search provider
spanway_fallbackThe fallback list of a model, used after retries on the primary fail
spanway_mcp_serverAn MCP server with its transport, authentication and allowed tools
spanway_credentialA stored credential that model deployments reference by name
spanway_vector_storeA vector store
spanway_jwt_key_mappingA mapping from a JWT claim value to a virtual key, so each JWT client inherits that key's models, budgets, limits and guardrails

A resource or argument marked as enterprise needs a Spanway enterprise license, and the named license feature where there is one. Without it the gateway refuses the call with a 403 that names the missing feature, so terraform apply fails on that object.

Keeping secrets out of state​

Sensitive arguments are hidden from plan output but still written in plaintext to the state file. With Terraform 1.11 or later, use the write-only versions instead. They are sent to the gateway and never stored in plan or state. spanway_credential takes credential_values_wo as a JSON string, and spanway_model takes model_api_key_wo, aws_secret_access_key_wo and vertex_credentials_wo, spanway_prompt takes api_key_wo, and spanway_mcp_server takes env_wo as a JSON string. Terraform cannot see a change to a write-only value, so bump the matching *_wo_version number when you rotate a secret.

resource "spanway_credential" "openai" {
credential_name = "openai-prod"
credential_values_wo = jsonencode({ api_key = var.openai_api_key })
credential_values_wo_version = 2
}

The key that spanway_key generates is already write-only.

Data sources​

Data sourceWhat it reads
spanway_model, spanway_modelsOne model deployment, or the list
spanway_team, spanway_teamsOne team, or a filtered list
spanway_organization, spanway_organizationsOne organization, or the list
spanway_user, spanway_usersOne user, or a page of users with server-side filters
spanway_key, spanway_keysOne key, or a filtered list
spanway_budget, spanway_budgetsOne budget, or all budgets
spanway_tag, spanway_tagsOne tag, or every stored and dynamic tag
spanway_project, spanway_projectsOne project, or every project visible to the caller
spanway_access_group, spanway_access_groupsOne model access group, or all of them
spanway_unified_access_group, spanway_unified_access_groupsOne unified access group, or all of them
spanway_guardrail, spanway_guardrailsOne guardrail, or every guardrail from config and database, without sensitive parameters
spanway_prompt, spanway_promptsOne prompt, or the list, without the provider key
spanway_agent, spanway_agentsOne A2A agent, or the list
spanway_search_tool, spanway_search_toolsOne search tool, or the list from database and config
spanway_fallbackThe fallback configuration of a model
spanway_mcp_server, spanway_mcp_serversOne MCP server, or the list
spanway_credentialOne stored credential
spanway_vector_storeOne vector store

Data sources are the way to reference objects created outside Terraform, for example a team created in the Admin UI that a Terraform-managed key should belong to.

Importing existing objects​

Every resource except the four membership ones (spanway_team_member, spanway_team_member_add, spanway_organization_member and spanway_organization_member_add) supports terraform import with the object's gateway id, which is how a gateway configured by hand is brought under Terraform without recreating its keys. Keys import by the token id the gateway assigned them.

Errors​

When the gateway refuses a call, Terraform shows the provider's message, which always starts with API request failed with status code <status>: followed by the gateway's answer. Secret fields in that answer (api_key, key, token, password, secret, credential and the provider key fields) are replaced with [REDACTED] before they reach your terminal or CI log.

What you seeWhat it meansFix
API request failed with status code 403: {"error": {"message": "... needs a Spanway enterprise license ..."}}The resource or argument needs a license feature the gateway lacks.Add the feature to the license, or remove the argument.
API request failed with status code 401: ... Authentication Error, Invalid proxy server token passed ...api_key is wrong, deleted or expired.Check SPANWAY_API_KEY, or create a new key.
API request failed with status code 401: ... Authentication Error, Only proxy admin can be used to generate, delete, update info for new keys/users/teams. ...api_key works but belongs to a user who is not a proxy admin.Use the master key or a proxy_admin user's key.
API request failed with status code 403: ... user not allowed to access this route ...The key's role may not call that management route.Use the master key or a proxy_admin user's key.
API request failed with status code 404: ...The object was deleted outside Terraform. On a refresh the provider treats a missing object as gone and plans to recreate it, so you only see this on a create or update that names another missing object, such as a team id.Check the id the resource points at, or create the missing object first.
API request failed with status code 422: ... or 400: ...The gateway rejected a value, for example a wrong type or an unknown model. The answer names the field.Fix the named argument and apply again.
error making request: ... connection refused or ... no such hostThe provider could not reach api_base.Check the URL, the port, DNS and any VPN or firewall between Terraform and the gateway.
error making request: ... Client.Timeout exceeded while awaiting headersThe gateway did not answer within request_timeout_seconds (120 by default).Check that the gateway is healthy, or raise request_timeout_seconds.
error parsing response JSON: ... followed by Response body: <html>...api_base points at something that is not the gateway, for example a load balancer error page or a login page.Point api_base at the gateway URL itself.
A certificate errorThe gateway uses a self-signed certificate.Use a trusted certificate, or set insecure_skip_verify on a development gateway only.
A secret changed but Terraform shows no diffWrite-only arguments are invisible to Terraform.Bump the matching *_wo_version.
Any error you cannot placeThe provider hides the HTTP exchange by default.Run with TF_LOG=DEBUG terraform apply and read the Logs section.

Logs​

The provider is quiet unless you ask Terraform for its debug log. Run TF_LOG=DEBUG terraform apply, or TF_LOG_PROVIDER=DEBUG terraform apply to see only the provider's lines, and add TF_LOG_PATH=terraform.log to write them to a file.

LineMeaningAction
Making POST request to https://gateway.example.com/key/generate with body: {...}The provider is about to call the gateway. The body is shown with secret fields replaced by [REDACTED].None. Use it to see which route and values each resource sends.
Response status: 200The gateway's HTTP status for that call.Anything other than 200 is followed by an error in the Terraform output.
Response body: {...}The gateway's answer, with secret fields replaced by [REDACTED].Read the error message here when the Terraform output is not enough.

Every call carries the header User-Agent: terraform-provider-spanway/<version>. Gateway access logs and load balancer logs show it, so you can tell Terraform changes from other calls. Gateway audit rows record the key that made a change rather than the User-Agent, so give Terraform its own admin key with an alias such as terraform, and the audit log then shows exactly which changes came from Terraform.