From 01c889ab4572b522f422680ae65490ff0ffcfe53 Mon Sep 17 00:00:00 2001 From: Sam Crang Date: Sun, 2 Jan 2022 20:25:43 +0000 Subject: [PATCH] Check to see if the project exists before creating keys (#99) Without this change if a user tries to create a Sentry key for a project that doesn't exist then they get a not very useful error message from `terraform apply`. For example, a Terraform resource that looks something like this: ``` resource "sentry_key" "test" { organization = "my-org" project = "project-that-does-not-exist" name = "test-sentry-fix" } ``` will produce this when `terraform apply` runs: ``` Error: EOF ``` If you set `TF_LOG=trace` then you get more info but still nothing particularly helpful: ``` apply errored, but we're indicating that via the Error pointer rather than returning it: EOF ``` This is because `resourceSentryKey` assumes that the project exists and that a 404 from the Sentry API must indicate that the key doesn't exist and should be created. However, if the project doesn't exist then we also get a 404 from the Sentry API and any attempt to create a key in that project that doesn't exist will fail. With this change the above error will be printed: ``` Error: project not found "project-that-does-not-exist": %!w() ``` In this specific case the error variable is `nil` so it's a bit weird but I think it's useful to display it for situations where it might not be `nil`. --- sentry/resource_sentry_key.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sentry/resource_sentry_key.go b/sentry/resource_sentry_key.go index 183508dc2..020c62241 100644 --- a/sentry/resource_sentry_key.go +++ b/sentry/resource_sentry_key.go @@ -1,6 +1,8 @@ package sentry import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/jianyuan/go-sentry/sentry" ) @@ -78,6 +80,12 @@ func resourceSentryKeyCreate(d *schema.ResourceData, meta interface{}) error { org := d.Get("organization").(string) project := d.Get("project").(string) + + _, resp, err := client.Projects.Get(org, project) + if found, err := checkClientGet(resp, err, d); !found { + return fmt.Errorf("project not found \"%v\": %w", project, err) + } + params := &sentry.CreateProjectKeyParams{ Name: d.Get("name").(string), RateLimit: &sentry.ProjectKeyRateLimit{