From bb0b8fb2a45f267ef577b79b380078b2b8c7974a Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Tue, 20 Oct 2020 18:05:37 +0000 Subject: [PATCH] add iam workload identity federation (#4071) Signed-off-by: Modular Magician --- .changelog/4071.txt | 3 + google-beta/config.go | 3 + google-beta/iam_beta_operation.go | 61 +++ google-beta/provider.go | 14 +- ...iam_beta-workload_identity_pool_id_test.go | 31 ++ ...esource_iam_beta_workload_identity_pool.go | 435 ++++++++++++++++++ ...a_workload_identity_pool_generated_test.go | 116 +++++ ...eta_workload_identity_pool_sweeper_test.go | 128 ++++++ ...ce_iam_beta_workload_identity_pool_test.go | 96 ++++ .../iam_workload_identity_pool.html.markdown | 148 ++++++ website/google.erb | 16 + 11 files changed, 1049 insertions(+), 2 deletions(-) create mode 100644 .changelog/4071.txt create mode 100644 google-beta/iam_beta_operation.go create mode 100644 google-beta/resource_iam_beta-workload_identity_pool_id_test.go create mode 100644 google-beta/resource_iam_beta_workload_identity_pool.go create mode 100644 google-beta/resource_iam_beta_workload_identity_pool_generated_test.go create mode 100644 google-beta/resource_iam_beta_workload_identity_pool_sweeper_test.go create mode 100644 google-beta/resource_iam_beta_workload_identity_pool_test.go create mode 100644 website/docs/r/iam_workload_identity_pool.html.markdown diff --git a/.changelog/4071.txt b/.changelog/4071.txt new file mode 100644 index 0000000000..9d1be23ff4 --- /dev/null +++ b/.changelog/4071.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_iam_workload_identity_pool` +``` diff --git a/google-beta/config.go b/google-beta/config.go index 9f1d6ae18a..0937bb457b 100644 --- a/google-beta/config.go +++ b/google-beta/config.go @@ -118,6 +118,7 @@ type Config struct { FirestoreBasePath string GameServicesBasePath string HealthcareBasePath string + IAMBetaBasePath string IapBasePath string IdentityPlatformBasePath string KMSBasePath string @@ -202,6 +203,7 @@ var FirebaseDefaultBasePath = "https://firebase.googleapis.com/v1beta1/" var FirestoreDefaultBasePath = "https://firestore.googleapis.com/v1/" var GameServicesDefaultBasePath = "https://gameservices.googleapis.com/v1beta/" var HealthcareDefaultBasePath = "https://healthcare.googleapis.com/v1beta1/" +var IAMBetaDefaultBasePath = "https://iam.googleapis.com/v1beta/" var IapDefaultBasePath = "https://iap.googleapis.com/v1/" var IdentityPlatformDefaultBasePath = "https://identitytoolkit.googleapis.com/v2/" var KMSDefaultBasePath = "https://cloudkms.googleapis.com/v1/" @@ -996,6 +998,7 @@ func ConfigureBasePaths(c *Config) { c.FirestoreBasePath = FirestoreDefaultBasePath c.GameServicesBasePath = GameServicesDefaultBasePath c.HealthcareBasePath = HealthcareDefaultBasePath + c.IAMBetaBasePath = IAMBetaDefaultBasePath c.IapBasePath = IapDefaultBasePath c.IdentityPlatformBasePath = IdentityPlatformDefaultBasePath c.KMSBasePath = KMSDefaultBasePath diff --git a/google-beta/iam_beta_operation.go b/google-beta/iam_beta_operation.go new file mode 100644 index 0000000000..1b9709297c --- /dev/null +++ b/google-beta/iam_beta_operation.go @@ -0,0 +1,61 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- +package google + +import ( + "fmt" + "time" +) + +type IAMBetaOperationWaiter struct { + Config *Config + UserAgent string + Project string + CommonOperationWaiter +} + +func (w *IAMBetaOperationWaiter) QueryOp() (interface{}, error) { + if w == nil { + return nil, fmt.Errorf("Cannot query operation, it's unset or nil.") + } + // Returns the proper get. + url := fmt.Sprintf("https://iam.googleapis.com/v1beta/%s", w.CommonOperationWaiter.Op.Name) + + return sendRequest(w.Config, "GET", w.Project, url, w.UserAgent, nil) +} + +func createIAMBetaWaiter(config *Config, op map[string]interface{}, project, activity, userAgent string) (*IAMBetaOperationWaiter, error) { + if val, ok := op["name"]; !ok || val == "" { + // This was a synchronous call - there is no operation to wait for. + return nil, nil + } + w := &IAMBetaOperationWaiter{ + Config: config, + UserAgent: userAgent, + Project: project, + } + if err := w.CommonOperationWaiter.SetOp(op); err != nil { + return nil, err + } + return w, nil +} + +func iAMBetaOperationWaitTime(config *Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error { + w, err := createIAMBetaWaiter(config, op, project, activity, userAgent) + if err != nil || w == nil { + // If w is nil, the op was synchronous. + return err + } + return OperationWait(w, activity, timeout, config.PollInterval) +} diff --git a/google-beta/provider.go b/google-beta/provider.go index b8545f88be..5e45d57f73 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -415,6 +415,14 @@ func Provider() *schema.Provider { "GOOGLE_HEALTHCARE_CUSTOM_ENDPOINT", }, HealthcareDefaultBasePath), }, + "iam_beta_custom_endpoint": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateCustomEndpoint, + DefaultFunc: schema.MultiEnvDefaultFunc([]string{ + "GOOGLE_IAM_BETA_CUSTOM_ENDPOINT", + }, IAMBetaDefaultBasePath), + }, "iap_custom_endpoint": { Type: schema.TypeString, Optional: true, @@ -749,9 +757,9 @@ func Provider() *schema.Provider { return provider } -// Generated resources: 193 +// Generated resources: 194 // Generated IAM resources: 81 -// Total generated resources: 274 +// Total generated resources: 275 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -933,6 +941,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_healthcare_dicom_store": resourceHealthcareDicomStore(), "google_healthcare_fhir_store": resourceHealthcareFhirStore(), "google_healthcare_hl7_v2_store": resourceHealthcareHl7V2Store(), + "google_iam_workload_identity_pool": resourceIAMBetaWorkloadIdentityPool(), "google_iap_web_iam_binding": ResourceIamBinding(IapWebIamSchema, IapWebIamUpdaterProducer, IapWebIdParseFunc), "google_iap_web_iam_member": ResourceIamMember(IapWebIamSchema, IapWebIamUpdaterProducer, IapWebIdParseFunc), "google_iap_web_iam_policy": ResourceIamPolicy(IapWebIamSchema, IapWebIamUpdaterProducer, IapWebIdParseFunc), @@ -1255,6 +1264,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr config.FirestoreBasePath = d.Get("firestore_custom_endpoint").(string) config.GameServicesBasePath = d.Get("game_services_custom_endpoint").(string) config.HealthcareBasePath = d.Get("healthcare_custom_endpoint").(string) + config.IAMBetaBasePath = d.Get("iam_beta_custom_endpoint").(string) config.IapBasePath = d.Get("iap_custom_endpoint").(string) config.IdentityPlatformBasePath = d.Get("identity_platform_custom_endpoint").(string) config.KMSBasePath = d.Get("kms_custom_endpoint").(string) diff --git a/google-beta/resource_iam_beta-workload_identity_pool_id_test.go b/google-beta/resource_iam_beta-workload_identity_pool_id_test.go new file mode 100644 index 0000000000..464d56358c --- /dev/null +++ b/google-beta/resource_iam_beta-workload_identity_pool_id_test.go @@ -0,0 +1,31 @@ +package google + +import ( + "strings" + "testing" +) + +func TestValidateIAMBetaWorkloadIdentityPoolId(t *testing.T) { + x := []StringValidationTestCase{ + // No errors + {TestName: "basic", Value: "foobar"}, + {TestName: "with numbers", Value: "foobar123"}, + {TestName: "short", Value: "foos"}, + {TestName: "long", Value: "12345678901234567890123456789012"}, + {TestName: "has a hyphen", Value: "foo-bar"}, + + // With errors + {TestName: "empty", Value: "", ExpectError: true}, + {TestName: "starts with a gcp-", Value: "gcp-foobar", ExpectError: true}, + {TestName: "with uppercase", Value: "fooBar", ExpectError: true}, + {TestName: "has an slash", Value: "foo/bar", ExpectError: true}, + {TestName: "has an backslash", Value: "foo\bar", ExpectError: true}, + {TestName: "too short", Value: "foo", ExpectError: true}, + {TestName: "too long", Value: strings.Repeat("f", 33), ExpectError: true}, + } + + es := testStringValidationCases(x, validateWorkloadIdentityPoolId) + if len(es) > 0 { + t.Errorf("Failed to validate WorkloadIdentityPool names: %v", es) + } +} diff --git a/google-beta/resource_iam_beta_workload_identity_pool.go b/google-beta/resource_iam_beta_workload_identity_pool.go new file mode 100644 index 0000000000..86b830d393 --- /dev/null +++ b/google-beta/resource_iam_beta_workload_identity_pool.go @@ -0,0 +1,435 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "log" + "reflect" + "regexp" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +const workloadIdentityPoolIdRegexp = `^[0-9a-z-]+$` + +func validateWorkloadIdentityPoolId(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + if strings.HasPrefix(value, "gcp-") { + errors = append(errors, fmt.Errorf( + "%q (%q) can not start with \"gcp-\"", k, value)) + } + + if !regexp.MustCompile(workloadIdentityPoolIdRegexp).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q must contain only lowercase letters (a-z), numbers (0-9), or dashes (-)", k)) + } + + if len(value) < 4 { + errors = append(errors, fmt.Errorf( + "%q cannot be smaller than 4 characters", k)) + } + + if len(value) > 32 { + errors = append(errors, fmt.Errorf( + "%q cannot be greater than 32 characters", k)) + } + + return +} + +func resourceIAMBetaWorkloadIdentityPool() *schema.Resource { + return &schema.Resource{ + Create: resourceIAMBetaWorkloadIdentityPoolCreate, + Read: resourceIAMBetaWorkloadIdentityPoolRead, + Update: resourceIAMBetaWorkloadIdentityPoolUpdate, + Delete: resourceIAMBetaWorkloadIdentityPoolDelete, + + Importer: &schema.ResourceImporter{ + State: resourceIAMBetaWorkloadIdentityPoolImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(4 * time.Minute), + Update: schema.DefaultTimeout(4 * time.Minute), + Delete: schema.DefaultTimeout(4 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "workload_identity_pool_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateWorkloadIdentityPoolId, + Description: `The ID to use for the pool, which becomes the final component of the resource name. This +value should be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix +'gcp-' is reserved for use by Google, and may not be specified.`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `A description of the pool. Cannot exceed 256 characters.`, + }, + "disabled": { + Type: schema.TypeBool, + Optional: true, + Description: `Whether the pool is disabled. You cannot use a disabled pool to exchange tokens, or use +existing tokens to access resources. If the pool is re-enabled, existing tokens grant +access again.`, + }, + "display_name": { + Type: schema.TypeString, + Optional: true, + Description: `A display name for the pool. Cannot exceed 32 characters.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `The resource name of the pool as +'projects//locations/global/workloadIdentityPools/'.`, + }, + "state": { + Type: schema.TypeString, + Computed: true, + Description: `The state of the pool. +STATE_UNSPECIFIED: State unspecified. +ACTIVE: The pool is active, and may be used in Google Cloud policies. +DELETED: The pool is soft-deleted. Soft-deleted pools are permanently deleted after +approximately 30 days. You can restore a soft-deleted pool using +UndeleteWorkloadIdentityPool. You cannot reuse the ID of a soft-deleted pool until it is +permanently deleted. While a pool is deleted, you cannot use it to exchange tokens, or +use existing tokens to access resources. If the pool is undeleted, existing tokens grant +access again.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + } +} + +func resourceIAMBetaWorkloadIdentityPoolCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + displayNameProp, err := expandIAMBetaWorkloadIdentityPoolDisplayName(d.Get("display_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(displayNameProp)) && (ok || !reflect.DeepEqual(v, displayNameProp)) { + obj["displayName"] = displayNameProp + } + descriptionProp, err := expandIAMBetaWorkloadIdentityPoolDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + disabledProp, err := expandIAMBetaWorkloadIdentityPoolDisabled(d.Get("disabled"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("disabled"); !isEmptyValue(reflect.ValueOf(disabledProp)) && (ok || !reflect.DeepEqual(v, disabledProp)) { + obj["disabled"] = disabledProp + } + + url, err := replaceVars(d, config, "{{IAMBetaBasePath}}projects/{{project}}/locations/global/workloadIdentityPools?workloadIdentityPoolId={{workload_identity_pool_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new WorkloadIdentityPool: %#v", obj) + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return err + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return fmt.Errorf("Error creating WorkloadIdentityPool: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = iAMBetaOperationWaitTime( + config, res, project, "Creating WorkloadIdentityPool", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create WorkloadIdentityPool: %s", err) + } + + log.Printf("[DEBUG] Finished creating WorkloadIdentityPool %q: %#v", d.Id(), res) + + return resourceIAMBetaWorkloadIdentityPoolRead(d, meta) +} + +func resourceIAMBetaWorkloadIdentityPoolRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{IAMBetaBasePath}}projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return err + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("IAMBetaWorkloadIdentityPool %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading WorkloadIdentityPool: %s", err) + } + + if err := d.Set("state", flattenIAMBetaWorkloadIdentityPoolState(res["state"], d, config)); err != nil { + return fmt.Errorf("Error reading WorkloadIdentityPool: %s", err) + } + if err := d.Set("display_name", flattenIAMBetaWorkloadIdentityPoolDisplayName(res["displayName"], d, config)); err != nil { + return fmt.Errorf("Error reading WorkloadIdentityPool: %s", err) + } + if err := d.Set("description", flattenIAMBetaWorkloadIdentityPoolDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading WorkloadIdentityPool: %s", err) + } + if err := d.Set("name", flattenIAMBetaWorkloadIdentityPoolName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading WorkloadIdentityPool: %s", err) + } + if err := d.Set("disabled", flattenIAMBetaWorkloadIdentityPoolDisabled(res["disabled"], d, config)); err != nil { + return fmt.Errorf("Error reading WorkloadIdentityPool: %s", err) + } + + return nil +} + +func resourceIAMBetaWorkloadIdentityPoolUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return err + } + billingProject = project + + obj := make(map[string]interface{}) + displayNameProp, err := expandIAMBetaWorkloadIdentityPoolDisplayName(d.Get("display_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, displayNameProp)) { + obj["displayName"] = displayNameProp + } + descriptionProp, err := expandIAMBetaWorkloadIdentityPoolDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + disabledProp, err := expandIAMBetaWorkloadIdentityPoolDisabled(d.Get("disabled"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("disabled"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, disabledProp)) { + obj["disabled"] = disabledProp + } + + url, err := replaceVars(d, config, "{{IAMBetaBasePath}}projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating WorkloadIdentityPool %q: %#v", d.Id(), obj) + updateMask := []string{} + + if d.HasChange("display_name") { + updateMask = append(updateMask, "displayName") + } + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + + if d.HasChange("disabled") { + updateMask = append(updateMask, "disabled") + } + // updateMask is a URL parameter but not present in the schema, so replaceVars + // won't set it + url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) + if err != nil { + return err + } + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return fmt.Errorf("Error updating WorkloadIdentityPool %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating WorkloadIdentityPool %q: %#v", d.Id(), res) + } + + err = iAMBetaOperationWaitTime( + config, res, project, "Updating WorkloadIdentityPool", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + + return resourceIAMBetaWorkloadIdentityPoolRead(d, meta) +} + +func resourceIAMBetaWorkloadIdentityPoolDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return err + } + billingProject = project + + url, err := replaceVars(d, config, "{{IAMBetaBasePath}}projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting WorkloadIdentityPool %q", d.Id()) + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "WorkloadIdentityPool") + } + + err = iAMBetaOperationWaitTime( + config, res, project, "Deleting WorkloadIdentityPool", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting WorkloadIdentityPool %q: %#v", d.Id(), res) + return nil +} + +func resourceIAMBetaWorkloadIdentityPoolImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "projects/(?P[^/]+)/locations/global/workloadIdentityPools/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := replaceVars(d, config, "projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenIAMBetaWorkloadIdentityPoolState(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenIAMBetaWorkloadIdentityPoolDisplayName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenIAMBetaWorkloadIdentityPoolDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenIAMBetaWorkloadIdentityPoolName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenIAMBetaWorkloadIdentityPoolDisabled(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandIAMBetaWorkloadIdentityPoolDisplayName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandIAMBetaWorkloadIdentityPoolDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandIAMBetaWorkloadIdentityPoolDisabled(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} diff --git a/google-beta/resource_iam_beta_workload_identity_pool_generated_test.go b/google-beta/resource_iam_beta_workload_identity_pool_generated_test.go new file mode 100644 index 0000000000..660d26e59b --- /dev/null +++ b/google-beta/resource_iam_beta_workload_identity_pool_generated_test.go @@ -0,0 +1,116 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccIAMBetaWorkloadIdentityPool_iamWorkloadIdentityPoolBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersOiCS, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckIAMBetaWorkloadIdentityPoolDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccIAMBetaWorkloadIdentityPool_iamWorkloadIdentityPoolBasicExample(context), + }, + }, + }) +} + +func testAccIAMBetaWorkloadIdentityPool_iamWorkloadIdentityPoolBasicExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_iam_workload_identity_pool" "example" { + provider = google-beta + workload_identity_pool_id = "tf-test-example-pool%{random_suffix}" +} +`, context) +} + +func TestAccIAMBetaWorkloadIdentityPool_iamWorkloadIdentityPoolFullExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersOiCS, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckIAMBetaWorkloadIdentityPoolDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccIAMBetaWorkloadIdentityPool_iamWorkloadIdentityPoolFullExample(context), + }, + }, + }) +} + +func testAccIAMBetaWorkloadIdentityPool_iamWorkloadIdentityPoolFullExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_iam_workload_identity_pool" "example" { + provider = google-beta + workload_identity_pool_id = "tf-test-example-pool%{random_suffix}" + display_name = "Name of pool" + description = "Identity pool for automated test" + disabled = true +} +`, context) +} + +func testAccCheckIAMBetaWorkloadIdentityPoolDestroyProducer(t *testing.T) func(s *terraform.State) error { + return func(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_iam_workload_identity_pool" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{IAMBetaBasePath}}projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}") + if err != nil { + return err + } + + _, err = sendRequest(config, "GET", "", url, config.userAgent, nil) + if err == nil { + return fmt.Errorf("IAMBetaWorkloadIdentityPool still exists at %s", url) + } + } + + return nil + } +} diff --git a/google-beta/resource_iam_beta_workload_identity_pool_sweeper_test.go b/google-beta/resource_iam_beta_workload_identity_pool_sweeper_test.go new file mode 100644 index 0000000000..149d80ae9e --- /dev/null +++ b/google-beta/resource_iam_beta_workload_identity_pool_sweeper_test.go @@ -0,0 +1,128 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("IAMBetaWorkloadIdentityPool", &resource.Sweeper{ + Name: "IAMBetaWorkloadIdentityPool", + F: testSweepIAMBetaWorkloadIdentityPool, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepIAMBetaWorkloadIdentityPool(region string) error { + resourceName := "IAMBetaWorkloadIdentityPool" + log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) + + config, err := sharedConfigForRegion(region) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) + return err + } + + err = config.LoadAndValidate(context.Background()) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) + return err + } + + t := &testing.T{} + billingId := getTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://iam.googleapis.com/v1beta/projects/{{project}}/locations/global/workloadIdentityPools", "?")[0] + listUrl, err := replaceVars(d, config, listTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) + return nil + } + + res, err := sendRequest(config, "GET", config.Project, listUrl, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["workloadIdentityPools"] + if !ok { + log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") + return nil + } + + rl := resourceList.([]interface{}) + + log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) + // Keep count of items that aren't sweepable for logging. + nonPrefixCount := 0 + for _, ri := range rl { + obj := ri.(map[string]interface{}) + var name string + // Id detected in the delete URL, attempt to use id. + if obj["id"] != nil { + name = GetResourceNameFromSelfLink(obj["id"].(string)) + } else if obj["name"] != nil { + name = GetResourceNameFromSelfLink(obj["name"].(string)) + } else { + log.Printf("[INFO][SWEEPER_LOG] %s resource name and id were nil", resourceName) + return nil + } + // Skip resources that shouldn't be sweeped + if !isSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://iam.googleapis.com/v1beta/projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}" + deleteUrl, err := replaceVars(d, config, deleteTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) + return nil + } + deleteUrl = deleteUrl + name + + // Don't wait on operations as we may have a lot to delete + _, err = sendRequest(config, "DELETE", config.Project, deleteUrl, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) + } else { + log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) + } + } + + if nonPrefixCount > 0 { + log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) + } + + return nil +} diff --git a/google-beta/resource_iam_beta_workload_identity_pool_test.go b/google-beta/resource_iam_beta_workload_identity_pool_test.go new file mode 100644 index 0000000000..3c80038dd2 --- /dev/null +++ b/google-beta/resource_iam_beta_workload_identity_pool_test.go @@ -0,0 +1,96 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccIAMBetaWorkloadIdentityPool_full(t *testing.T) { + t.Parallel() + + randomSuffix := randString(t, 10) + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccIAMBetaWorkloadIdentityPool_full(randomSuffix), + }, + { + ResourceName: "google_iam_workload_identity_pool.my_pool", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIAMBetaWorkloadIdentityPool_update(randomSuffix), + }, + { + ResourceName: "google_iam_workload_identity_pool.my_pool", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccIAMBetaWorkloadIdentityPool_minimal(t *testing.T) { + t.Parallel() + + randomSuffix := randString(t, 10) + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccIAMBetaWorkloadIdentityPool_minimal(randomSuffix), + }, + { + ResourceName: "google_iam_workload_identity_pool.my_pool", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccIAMBetaWorkloadIdentityPool_update(randomSuffix), + }, + { + ResourceName: "google_iam_workload_identity_pool.my_pool", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccIAMBetaWorkloadIdentityPool_full(suffix string) string { + return fmt.Sprintf(` +resource "google_iam_workload_identity_pool" "my_pool" { + workload_identity_pool_id = "my-pool-%s" + display_name = "Name of pool" + description = "Identity pool for automated test" + disabled = true +} +`, suffix) +} + +func testAccIAMBetaWorkloadIdentityPool_minimal(suffix string) string { + return fmt.Sprintf(` +resource "google_iam_workload_identity_pool" "my_pool" { + workload_identity_pool_id = "my-pool-%s" +} +`, suffix) +} + +func testAccIAMBetaWorkloadIdentityPool_update(suffix string) string { + return fmt.Sprintf(` +resource "google_iam_workload_identity_pool" "my_pool" { + workload_identity_pool_id = "my-pool-%s" + display_name = "Updated name of pool" + description = "Updated description" + disabled = false +} +`, suffix) +} diff --git a/website/docs/r/iam_workload_identity_pool.html.markdown b/website/docs/r/iam_workload_identity_pool.html.markdown new file mode 100644 index 0000000000..a26bde55c5 --- /dev/null +++ b/website/docs/r/iam_workload_identity_pool.html.markdown @@ -0,0 +1,148 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +# +# ---------------------------------------------------------------------------- +# +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. +# +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. +# +# ---------------------------------------------------------------------------- +subcategory: "Cloud IAM" +layout: "google" +page_title: "Google: google_iam_workload_identity_pool" +sidebar_current: "docs-google-iam-workload-identity-pool" +description: |- + Represents a collection of external workload identities. +--- + +# google\_iam\_workload\_identity\_pool + +Represents a collection of external workload identities. You can define IAM policies to +grant these identities access to Google Cloud resources. + +~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. +See [Provider Versions](https://terraform.io/docs/providers/google/guides/provider_versions.html) for more details on beta resources. + +To get more information about WorkloadIdentityPool, see: + +* [API documentation](https://cloud.google.com/iam/docs/reference/rest/v1beta/projects.locations.workloadIdentityPools) +* How-to Guides + * [Managing workload identity pools](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#pools) + + +## Example Usage - Iam Workload Identity Pool Basic + + +```hcl +resource "google_iam_workload_identity_pool" "example" { + provider = google-beta + workload_identity_pool_id = "example-pool" +} +``` + +## Example Usage - Iam Workload Identity Pool Full + + +```hcl +resource "google_iam_workload_identity_pool" "example" { + provider = google-beta + workload_identity_pool_id = "example-pool" + display_name = "Name of pool" + description = "Identity pool for automated test" + disabled = true +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `workload_identity_pool_id` - + (Required) + The ID to use for the pool, which becomes the final component of the resource name. This + value should be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix + `gcp-` is reserved for use by Google, and may not be specified. + + +- - - + + +* `display_name` - + (Optional) + A display name for the pool. Cannot exceed 32 characters. + +* `description` - + (Optional) + A description of the pool. Cannot exceed 256 characters. + +* `disabled` - + (Optional) + Whether the pool is disabled. You cannot use a disabled pool to exchange tokens, or use + existing tokens to access resources. If the pool is re-enabled, existing tokens grant + access again. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}` + +* `state` - + The state of the pool. + STATE_UNSPECIFIED: State unspecified. + ACTIVE: The pool is active, and may be used in Google Cloud policies. + DELETED: The pool is soft-deleted. Soft-deleted pools are permanently deleted after + approximately 30 days. You can restore a soft-deleted pool using + UndeleteWorkloadIdentityPool. You cannot reuse the ID of a soft-deleted pool until it is + permanently deleted. While a pool is deleted, you cannot use it to exchange tokens, or + use existing tokens to access resources. If the pool is undeleted, existing tokens grant + access again. + +* `name` - + The resource name of the pool as + `projects//locations/global/workloadIdentityPools/`. + + +* `self_link`: The self link of the created WorkloadIdentityPool in the format `projects/{project}/locations/global/workloadIdentityPools/{workload_identity_pool_id}` + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `update` - Default is 4 minutes. +- `delete` - Default is 4 minutes. + +## Import + + +WorkloadIdentityPool can be imported using any of these accepted formats: + +``` +$ terraform import google_iam_workload_identity_pool.default projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}} +$ terraform import google_iam_workload_identity_pool.default {{project}}/{{workload_identity_pool_id}} +$ terraform import google_iam_workload_identity_pool.default {{workload_identity_pool_id}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override). diff --git a/website/google.erb b/website/google.erb index 7b30040a6f..eff8dd12a8 100644 --- a/website/google.erb +++ b/website/google.erb @@ -735,6 +735,22 @@ +
  • + Cloud IAM + +
  • +
  • Cloud Identity