Skip to content

fix(terraform): drop litellm_key from state on 404 instead of failing the plan - #40443

Merged
yassin-berriai merged 2 commits into
litellm_internal_stagingfrom
litellm_tf_key_read_404
Sep 10, 2026
Merged

yassin-berriai merged 2 commits into
litellm_internal_stagingfrom
litellm_tf_key_read_404

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A litellm_key deleted or rotated outside Terraform 404s on refresh
  • That 404 fails the whole terraform plan, blocking every other resource too

How it solves it:

  • /key/info 404 on refresh now clears the key from state
  • Terraform then plans a recreate (or the operator imports the rotated id)
  • Every other status (401, 500, ...) still fails the plan as before

User Flow

Before: a platform team manages virtual keys with Terraform, someone deletes one key in the Admin UI, and from then on every plan in that workspace errors out

  1. They apply a config with litellm_key.tf_managed (alias tf-managed-lit-6394) and litellm_team.unrelated, both create fine
  2. A teammate deletes the key via POST http://localhost:4000/key/delete, response {"deleted_keys":["tf-managed-lit-6394"]}
  3. GET http://localhost:4000/key/info?key= now returns 404 Key not found in database
  4. They run terraform plan and get Error: error reading key: API request failed with status code 404 ..., exit 1, with no plan for any resource
  5. The same thing happens after POST http://localhost:4000/key/regenerate, because the old token_id in state no longer resolves

After: the same plan succeeds and shows the missing key as + create, so the team can recreate it (or import the rotated one) without hand-editing state

  1. They apply the same config, both resources create fine
  2. A teammate deletes the key via POST http://localhost:4000/key/delete, response {"deleted_keys":["tf-managed-lit-6394"]}
  3. GET http://localhost:4000/key/info?key= returns 404 Key not found in database
  4. They run terraform plan, it exits 0 with Plan: 1 to add, 0 to change, 0 to destroy. and litellm_key.tf_managed will be created
  5. terraform apply creates the key again, and the next terraform plan says No changes.
  6. After a regenerate, plan also exits 0 with a + create. Since the rotated key still holds the alias, they run terraform import litellm_key.tf_managed <new token_id> and the next plan says No changes.

Relevant issues

Fixes BerriAI/terraform-provider-litellm#51

Linear ticket

Resolves LIT-6394

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. cd terraform/provider && go test -timeout 120s ./...
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

Root cause: sendRequest folded every non-200 into a plain fmt.Errorf, so GetKey could never tell a 404 apart from any other failure and resourceKeyRead always returned a hard diagnostic; the existing if key == nil { d.SetId("") } branch was unreachable. The fix returns a typed apiError{StatusCode, Body} from sendRequest (same message text as before, so every other caller is unchanged), and GetKey maps only StatusCode == 404 to (nil, nil)

Setup, shared by both arms: local proxy on http://localhost:4000 with Postgres, started from this checkout with PYTHONPATH=<checkout> uv run --no-sync litellm --config litellm/proxy/dev_config.yaml --port 4000 --use_prisma_db_push. Terraform 1.13.4 with a dev_overrides CLI config pointing at a provider binary built with go build from the named commit (asserted with strings <binary> | grep "not found, removing from state": 0 hits for Before, 7 for After). Same main.tf and the same state file across arms:

provider "litellm" {
  api_base = "http://localhost:4000"
  api_key  = "sk-1234"
}

resource "litellm_key" "tf_managed" {
  key_alias = "tf-managed-lit-6394"
  models    = ["anthropic-haiku-4-5"]
}

resource "litellm_team" "unrelated" {
  team_alias = "tf-unrelated-lit-6394"
}

Before (096984b)

Key deleted out of band

  1. curl -s -X POST -H "Authorization: Bearer $MASTER" -H 'Content-Type: application/json' http://localhost:4000/key/delete -d '{"key_aliases":["tf-managed-lit-6394"]}'
    {"deleted_keys":["tf-managed-lit-6394"]}
    
  2. curl -s -w '\n%{http_code}\n' -H "Authorization: Bearer $MASTER" 'http://localhost:4000/key/info?key=4c6036efed3c5f8ace928128479bf6aee089206b1f6f723a15b44ee9df816eb6'
    {"error":{"message":"Key not found in database","type":"not_found_error","param":"key","code":"404"}}
    404
    
  3. terraform plan -no-color
    litellm_team.unrelated: Refreshing state... [id=d930035c-7f8f-4333-a19a-e0f1c345e34a]
    litellm_key.tf_managed: Refreshing state... [id=4c6036efed3c5f8ace928128479bf6aee089206b1f6f723a15b44ee9df816eb6]
    
    Planning failed. Terraform encountered an error while generating this plan.
    
    Error: error reading key: API request failed with status code 404: {"error":{"message":"Key not found in database","type":"not_found_error","param":"key","code":"404"}}
    
      with litellm_key.tf_managed,
      on main.tf line 14, in resource "litellm_key" "tf_managed":
      14: resource "litellm_key" "tf_managed" {
    
    exit=1
    

Key rotated out of band

  1. curl -s -X POST -H "Authorization: Bearer $MASTER" -H 'Content-Type: application/json' http://localhost:4000/key/regenerate -d '{"key":"<current key>"}' returns a new token_id 7a356d5d..., and /key/info for the old id 31e0c87d... returns 404 as above
  2. terraform plan -no-color
    litellm_team.unrelated: Refreshing state... [id=d930035c-7f8f-4333-a19a-e0f1c345e34a]
    litellm_key.tf_managed: Refreshing state... [id=31e0c87db847a3f4dbcbaf1dde58587fe79b94f8af051bb69c996a555a22b6a3]
    
    Planning failed. Terraform encountered an error while generating this plan.
    
    Error: error reading key: API request failed with status code 404: {"error":{"message":"Key not found in database","type":"not_found_error","param":"key","code":"404"}}
    exit=1
    

Non-404 error (provider api_key = "sk-wrong")

  1. terraform plan -no-color
    Planning failed. Terraform encountered an error while generating this plan.
    Error: error reading key: API request failed with status code 401: {"error":{"message":"Authentication Error, Invalid proxy server token passed. ...
    exit=1
    

After (69105f2)

Key deleted out of band

  1. curl -s -X POST -H "Authorization: Bearer $MASTER" -H 'Content-Type: application/json' http://localhost:4000/key/delete -d '{"key_aliases":["tf-managed-lit-6394"]}'
    {"deleted_keys":["tf-managed-lit-6394"]}
    
  2. curl -s -w '\n%{http_code}\n' -H "Authorization: Bearer $MASTER" 'http://localhost:4000/key/info?key=7a356d5da23abe5e8e16f3e054b94c0946ed0821e2269844f53d2cd7bd0c03fc'
    {"error":{"message":"Key not found in database","type":"not_found_error","param":"key","code":"404"}}
    404
    
  3. terraform plan -no-color
    litellm_key.tf_managed: Refreshing state... [id=7a356d5da23abe5e8e16f3e054b94c0946ed0821e2269844f53d2cd7bd0c03fc]
    litellm_team.unrelated: Refreshing state... [id=d930035c-7f8f-4333-a19a-e0f1c345e34a]
      # litellm_key.tf_managed will be created
    Plan: 1 to add, 0 to change, 0 to destroy.
    exit=0
    
  4. terraform apply -auto-approve -no-color
    litellm_key.tf_managed: Creating...
    litellm_key.tf_managed: Creation complete after 0s [id=58326680712c176167c6fc67ff09d36c84502210c0c31d6ed60fc6f760fef8c7]
    Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
    exit=0
    
  5. terraform plan -no-color
    litellm_key.tf_managed: Refreshing state... [id=58326680712c176167c6fc67ff09d36c84502210c0c31d6ed60fc6f760fef8c7]
    litellm_team.unrelated: Refreshing state... [id=d930035c-7f8f-4333-a19a-e0f1c345e34a]
    No changes. Your infrastructure matches the configuration.
    exit=0
    

Key rotated out of band

  1. State holds the rotated-away id 31e0c87d..., /key/info for it returns 404 as above
  2. terraform plan -no-color
    litellm_team.unrelated: Refreshing state... [id=d930035c-7f8f-4333-a19a-e0f1c345e34a]
    litellm_key.tf_managed: Refreshing state... [id=31e0c87db847a3f4dbcbaf1dde58587fe79b94f8af051bb69c996a555a22b6a3]
    
    Terraform will perform the following actions:
    
      # litellm_key.tf_managed will be created
      + resource "litellm_key" "tf_managed" {
          + id                    = (known after apply)
          + key_alias             = "tf-managed-lit-6394"
          + models                = [
              + "anthropic-haiku-4-5",
            ]
          + token_id              = (known after apply)
        }
    
    Plan: 1 to add, 0 to change, 0 to destroy.
    exit=0
    
  3. terraform apply -auto-approve -no-color (the rotated key still owns the alias, so the proxy rejects the recreate; this is the existing alias-uniqueness rule, unchanged by this PR)
    litellm_key.tf_managed: Creating...
    Error: error creating key: API request failed with status code 400: {"error":{"message":"Key with alias 'tf-managed-lit-6394' already exists. Unique key aliases across all keys are required.","type":"bad_request_error","param":"key_alias","code":"400"}}
    exit=1
    
  4. terraform import litellm_key.tf_managed 7a356d5da23abe5e8e16f3e054b94c0946ed0821e2269844f53d2cd7bd0c03fc
    litellm_key.tf_managed: Refreshing state... [id=7a356d5da23abe5e8e16f3e054b94c0946ed0821e2269844f53d2cd7bd0c03fc]
    Import successful!
    
  5. terraform plan -no-color
    litellm_team.unrelated: Refreshing state... [id=d930035c-7f8f-4333-a19a-e0f1c345e34a]
    litellm_key.tf_managed: Refreshing state... [id=7a356d5da23abe5e8e16f3e054b94c0946ed0821e2269844f53d2cd7bd0c03fc]
    No changes. Your infrastructure matches the configuration.
    exit=0
    

Non-404 error (provider api_key = "sk-wrong")

  1. terraform plan -no-color
    litellm_team.unrelated: Refreshing state... [id=d930035c-7f8f-4333-a19a-e0f1c345e34a]
    litellm_key.tf_managed: Refreshing state... [id=58326680712c176167c6fc67ff09d36c84502210c0c31d6ed60fc6f760fef8c7]
    Planning failed. Terraform encountered an error while generating this plan.
    Error: error reading key: API request failed with status code 401: {"error":{"message":"Authentication Error, Invalid proxy server token passed. ...
    exit=1
    

Tests: TestResourceKeyReadDropsMissingKeyFromState and TestResourceKeyReadStillFailsOnNon404Errors in terraform/provider/litellm/resource_key_test.go. Mutation check: reverting client.go to the merge base, keeping the old fmt.Errorf in sendRequest, or widening isNotFound to any apiError each fail exactly one of the two tests. gofmt -l, go vet ./..., go build ./..., and go test -timeout 120s ./... pass on the tip

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Rotation still needs a terraform import of the new token_id, since the rotated key keeps the alias
  • Only the litellm_key read path changes. Other resources already handled 404 with d.SetId("")

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/a3cc1cc6dd8b45928c3c6e0258317eae
Open in Devin Desktop: https://app.devin.ai/desktop/session/a3cc1cc6dd8b45928c3c6e0258317eae?variant=devin
Requested by: @yassin-berriai

… the plan

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR allows Terraform refresh to treat a missing LiteLLM key as an absent resource rather than aborting the plan.

  • Introduces a typed API error carrying the HTTP status and response body while preserving existing error messages.
  • Maps /key/info 404 responses to a missing key so Terraform removes the stale resource ID from state.
  • Adds regression coverage showing that 404 clears state while non-404 failures remain errors.

Confidence Score: 5/5

The PR appears safe to merge because it narrowly handles missing keys during refresh while preserving failures for all other HTTP statuses.

No actionable failures remain: the typed error preserves existing caller-visible messages, the endpoint’s 404 contract represents an absent key, and tests cover both the intended 404 behavior and a non-404 failure.

Important Files Changed

Filename Overview
terraform/provider/litellm/client.go Adds typed HTTP errors and maps key-info 404 responses to an absent key without changing handling for other statuses.
terraform/provider/litellm/resource_key.go Logs when a missing key is removed from Terraform state through the existing nil-key branch.
terraform/provider/litellm/resource_key_test.go Covers state removal on 404 and preservation of the existing failure behavior and state ID on 500 responses.

Reviews (1): Last reviewed commit: "fix(terraform): drop litellm_key from st..." | Re-trigger Greptile

@codecov

codecov Bot commented Sep 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yassin-berriai
yassin-berriai enabled auto-merge (squash) September 10, 2026 02:46
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@yassin-berriai
yassin-berriai merged commit 5264f8e into litellm_internal_staging Sep 10, 2026
82 of 83 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_tf_key_read_404 branch September 10, 2026 02:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: a key deleted or rotated outside Terraform triggers a hard 404 that blocks all plan/apply

3 participants