diff --git a/.changelog/6389.txt b/.changelog/6389.txt new file mode 100644 index 00000000000..02adfd8fb66 --- /dev/null +++ b/.changelog/6389.txt @@ -0,0 +1,9 @@ +```release-note:new-resource +google_gke_hub_membership_iam_binding +``` +```release-note:new-resource +google_gke_hub_membership_iam_member +``` +```release-note:new-resource +google_gke_hub_membership_iam_policy +``` diff --git a/google/iam_gke_hub_membership.go b/google/iam_gke_hub_membership.go new file mode 100644 index 00000000000..25ed167af3c --- /dev/null +++ b/google/iam_gke_hub_membership.go @@ -0,0 +1,198 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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" + + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "google.golang.org/api/cloudresourcemanager/v1" +) + +var GKEHubMembershipIamSchema = map[string]*schema.Schema{ + "project": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + }, + "membership_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + }, +} + +type GKEHubMembershipIamUpdater struct { + project string + membershipId string + d TerraformResourceData + Config *Config +} + +func GKEHubMembershipIamUpdaterProducer(d TerraformResourceData, config *Config) (ResourceIamUpdater, error) { + values := make(map[string]string) + + project, _ := getProject(d, config) + if project != "" { + if err := d.Set("project", project); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + } + values["project"] = project + if v, ok := d.GetOk("membership_id"); ok { + values["membership_id"] = v.(string) + } + + // We may have gotten either a long or short name, so attempt to parse long name if possible + m, err := getImportIdQualifiers([]string{"projects/(?P[^/]+)/locations/(?P[^/]+)/memberships/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Get("membership_id").(string)) + if err != nil { + return nil, err + } + + for k, v := range m { + values[k] = v + } + + u := &GKEHubMembershipIamUpdater{ + project: values["project"], + membershipId: values["membership_id"], + d: d, + Config: config, + } + + if err := d.Set("project", u.project); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + if err := d.Set("membership_id", u.GetResourceId()); err != nil { + return nil, fmt.Errorf("Error setting membership_id: %s", err) + } + + return u, nil +} + +func GKEHubMembershipIdParseFunc(d *schema.ResourceData, config *Config) error { + values := make(map[string]string) + + project, _ := getProject(d, config) + if project != "" { + values["project"] = project + } + + m, err := getImportIdQualifiers([]string{"projects/(?P[^/]+)/locations/(?P[^/]+)/memberships/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Id()) + if err != nil { + return err + } + + for k, v := range m { + values[k] = v + } + + u := &GKEHubMembershipIamUpdater{ + project: values["project"], + membershipId: values["membership_id"], + d: d, + Config: config, + } + if err := d.Set("membership_id", u.GetResourceId()); err != nil { + return fmt.Errorf("Error setting membership_id: %s", err) + } + d.SetId(u.GetResourceId()) + return nil +} + +func (u *GKEHubMembershipIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { + url, err := u.qualifyMembershipUrl("getIamPolicy") + if err != nil { + return nil, err + } + + project, err := getProject(u.d, u.Config) + if err != nil { + return nil, err + } + var obj map[string]interface{} + + userAgent, err := generateUserAgentString(u.d, u.Config.userAgent) + if err != nil { + return nil, err + } + + policy, err := sendRequest(u.Config, "GET", project, url, userAgent, obj) + if err != nil { + return nil, errwrap.Wrapf(fmt.Sprintf("Error retrieving IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + out := &cloudresourcemanager.Policy{} + err = Convert(policy, out) + if err != nil { + return nil, errwrap.Wrapf("Cannot convert a policy to a resource manager policy: {{err}}", err) + } + + return out, nil +} + +func (u *GKEHubMembershipIamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error { + json, err := ConvertToMap(policy) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + obj["policy"] = json + + url, err := u.qualifyMembershipUrl("setIamPolicy") + if err != nil { + return err + } + project, err := getProject(u.d, u.Config) + if err != nil { + return err + } + + userAgent, err := generateUserAgentString(u.d, u.Config.userAgent) + if err != nil { + return err + } + + _, err = sendRequestWithTimeout(u.Config, "POST", project, url, userAgent, obj, u.d.Timeout(schema.TimeoutCreate)) + if err != nil { + return errwrap.Wrapf(fmt.Sprintf("Error setting IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + return nil +} + +func (u *GKEHubMembershipIamUpdater) qualifyMembershipUrl(methodIdentifier string) (string, error) { + urlTemplate := fmt.Sprintf("{{GKEHubBasePath}}%s:%s", fmt.Sprintf("projects/%s/locations/global/memberships/%s", u.project, u.membershipId), methodIdentifier) + url, err := replaceVars(u.d, u.Config, urlTemplate) + if err != nil { + return "", err + } + return url, nil +} + +func (u *GKEHubMembershipIamUpdater) GetResourceId() string { + return fmt.Sprintf("projects/%s/locations/global/memberships/%s", u.project, u.membershipId) +} + +func (u *GKEHubMembershipIamUpdater) GetMutexKey() string { + return fmt.Sprintf("iam-gkehub-membership-%s", u.GetResourceId()) +} + +func (u *GKEHubMembershipIamUpdater) DescribeResource() string { + return fmt.Sprintf("gkehub membership %q", u.GetResourceId()) +} diff --git a/google/iam_gke_hub_membership_generated_test.go b/google/iam_gke_hub_membership_generated_test.go new file mode 100644 index 00000000000..dac247b7f35 --- /dev/null +++ b/google/iam_gke_hub_membership_generated_test.go @@ -0,0 +1,255 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccGKEHubMembershipIamBindingGenerated(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/viewer", + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccGKEHubMembershipIamBinding_basicGenerated(context), + }, + { + ResourceName: "google_gke_hub_membership_iam_binding.foo", + ImportStateId: fmt.Sprintf("projects/%s/locations/%s/memberships/%s roles/viewer", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("basic%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + { + // Test Iam Binding update + Config: testAccGKEHubMembershipIamBinding_updateGenerated(context), + }, + { + ResourceName: "google_gke_hub_membership_iam_binding.foo", + ImportStateId: fmt.Sprintf("projects/%s/locations/%s/memberships/%s roles/viewer", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("basic%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccGKEHubMembershipIamMemberGenerated(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/viewer", + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + // Test Iam Member creation (no update for member, no need to test) + Config: testAccGKEHubMembershipIamMember_basicGenerated(context), + }, + { + ResourceName: "google_gke_hub_membership_iam_member.foo", + ImportStateId: fmt.Sprintf("projects/%s/locations/%s/memberships/%s roles/viewer user:admin@hashicorptest.com", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("basic%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccGKEHubMembershipIamPolicyGenerated(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/viewer", + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccGKEHubMembershipIamPolicy_basicGenerated(context), + }, + { + ResourceName: "google_gke_hub_membership_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/locations/%s/memberships/%s", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("basic%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccGKEHubMembershipIamPolicy_emptyBinding(context), + }, + { + ResourceName: "google_gke_hub_membership_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/locations/%s/memberships/%s", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("basic%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccGKEHubMembershipIamMember_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_container_cluster" "primary" { + name = "basiccluster%{random_suffix}" + location = "us-central1-a" + initial_node_count = 1 +} + +resource "google_gke_hub_membership" "membership" { + membership_id = "basic%{random_suffix}" + endpoint { + gke_cluster { + resource_link = "//container.googleapis.com/${google_container_cluster.primary.id}" + } + } +} + +resource "google_gke_hub_membership_iam_member" "foo" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + role = "%{role}" + member = "user:admin@hashicorptest.com" +} +`, context) +} + +func testAccGKEHubMembershipIamPolicy_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_container_cluster" "primary" { + name = "basiccluster%{random_suffix}" + location = "us-central1-a" + initial_node_count = 1 +} + +resource "google_gke_hub_membership" "membership" { + membership_id = "basic%{random_suffix}" + endpoint { + gke_cluster { + resource_link = "//container.googleapis.com/${google_container_cluster.primary.id}" + } + } +} + +data "google_iam_policy" "foo" { + binding { + role = "%{role}" + members = ["user:admin@hashicorptest.com"] + } +} + +resource "google_gke_hub_membership_iam_policy" "foo" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccGKEHubMembershipIamPolicy_emptyBinding(context map[string]interface{}) string { + return Nprintf(` +resource "google_container_cluster" "primary" { + name = "basiccluster%{random_suffix}" + location = "us-central1-a" + initial_node_count = 1 +} + +resource "google_gke_hub_membership" "membership" { + membership_id = "basic%{random_suffix}" + endpoint { + gke_cluster { + resource_link = "//container.googleapis.com/${google_container_cluster.primary.id}" + } + } +} + +data "google_iam_policy" "foo" { +} + +resource "google_gke_hub_membership_iam_policy" "foo" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccGKEHubMembershipIamBinding_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_container_cluster" "primary" { + name = "basiccluster%{random_suffix}" + location = "us-central1-a" + initial_node_count = 1 +} + +resource "google_gke_hub_membership" "membership" { + membership_id = "basic%{random_suffix}" + endpoint { + gke_cluster { + resource_link = "//container.googleapis.com/${google_container_cluster.primary.id}" + } + } +} + +resource "google_gke_hub_membership_iam_binding" "foo" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + role = "%{role}" + members = ["user:admin@hashicorptest.com"] +} +`, context) +} + +func testAccGKEHubMembershipIamBinding_updateGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_container_cluster" "primary" { + name = "basiccluster%{random_suffix}" + location = "us-central1-a" + initial_node_count = 1 +} + +resource "google_gke_hub_membership" "membership" { + membership_id = "basic%{random_suffix}" + endpoint { + gke_cluster { + resource_link = "//container.googleapis.com/${google_container_cluster.primary.id}" + } + } +} + +resource "google_gke_hub_membership_iam_binding" "foo" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + role = "%{role}" + members = ["user:admin@hashicorptest.com", "user:gterraformtest1@gmail.com"] +} +`, context) +} diff --git a/google/provider.go b/google/provider.go index e3f5d9e34a3..7f0d358fd63 100644 --- a/google/provider.go +++ b/google/provider.go @@ -873,8 +873,8 @@ func Provider() *schema.Provider { } // Generated resources: 228 -// Generated IAM resources: 132 -// Total generated resources: 360 +// Generated IAM resources: 135 +// Total generated resources: 363 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -1100,6 +1100,9 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_game_services_game_server_config": resourceGameServicesGameServerConfig(), "google_game_services_game_server_deployment_rollout": resourceGameServicesGameServerDeploymentRollout(), "google_gke_hub_membership": resourceGKEHubMembership(), + "google_gke_hub_membership_iam_binding": ResourceIamBinding(GKEHubMembershipIamSchema, GKEHubMembershipIamUpdaterProducer, GKEHubMembershipIdParseFunc), + "google_gke_hub_membership_iam_member": ResourceIamMember(GKEHubMembershipIamSchema, GKEHubMembershipIamUpdaterProducer, GKEHubMembershipIdParseFunc), + "google_gke_hub_membership_iam_policy": ResourceIamPolicy(GKEHubMembershipIamSchema, GKEHubMembershipIamUpdaterProducer, GKEHubMembershipIdParseFunc), "google_healthcare_dataset": resourceHealthcareDataset(), "google_healthcare_dicom_store": resourceHealthcareDicomStore(), "google_healthcare_fhir_store": resourceHealthcareFhirStore(), diff --git a/website/docs/r/gke_hub_membership_iam.html.markdown b/website/docs/r/gke_hub_membership_iam.html.markdown new file mode 100644 index 00000000000..c44f5eff82f --- /dev/null +++ b/website/docs/r/gke_hub_membership_iam.html.markdown @@ -0,0 +1,145 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** Type: MMv1 *** +# +# ---------------------------------------------------------------------------- +# +# 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: "GKEHub" +page_title: "Google: google_gke_hub_membership_iam" +description: |- + Collection of resources to manage IAM policy for GKEHub Membership +--- + +# IAM policy for GKEHub Membership +Three different resources help you manage your IAM policy for GKEHub Membership. Each of these resources serves a different use case: + +* `google_gke_hub_membership_iam_policy`: Authoritative. Sets the IAM policy for the membership and replaces any existing policy already attached. +* `google_gke_hub_membership_iam_binding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the membership are preserved. +* `google_gke_hub_membership_iam_member`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the membership are preserved. + +~> **Note:** `google_gke_hub_membership_iam_policy` **cannot** be used in conjunction with `google_gke_hub_membership_iam_binding` and `google_gke_hub_membership_iam_member` or they will fight over what your policy should be. + +~> **Note:** `google_gke_hub_membership_iam_binding` resources **can be** used in conjunction with `google_gke_hub_membership_iam_member` resources **only if** they do not grant privilege to the same role. + + + + +## google\_gke\_hub\_membership\_iam\_policy + +```hcl +data "google_iam_policy" "admin" { + binding { + role = "roles/viewer" + members = [ + "user:jane@example.com", + ] + } +} + +resource "google_gke_hub_membership_iam_policy" "policy" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + policy_data = data.google_iam_policy.admin.policy_data +} +``` + +## google\_gke\_hub\_membership\_iam\_binding + +```hcl +resource "google_gke_hub_membership_iam_binding" "binding" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + role = "roles/viewer" + members = [ + "user:jane@example.com", + ] +} +``` + +## google\_gke\_hub\_membership\_iam\_member + +```hcl +resource "google_gke_hub_membership_iam_member" "member" { + project = google_gke_hub_membership.membership.project + membership_id = google_gke_hub_membership.membership.membership_id + role = "roles/viewer" + member = "user:jane@example.com" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. + +* `member/members` - (Required) Identities that will be granted the privilege in `role`. + Each entry can have one of the following values: + * **allUsers**: A special identifier that represents anyone who is on the internet; with or without a Google account. + * **allAuthenticatedUsers**: A special identifier that represents anyone who is authenticated with a Google account or a service account. + * **user:{emailid}**: An email address that represents a specific Google account. For example, alice@gmail.com or joe@example.com. + * **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com. + * **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com. + * **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com. + * **projectOwner:projectid**: Owners of the given project. For example, "projectOwner:my-example-project" + * **projectEditor:projectid**: Editors of the given project. For example, "projectEditor:my-example-project" + * **projectViewer:projectid**: Viewers of the given project. For example, "projectViewer:my-example-project" + +* `role` - (Required) The role that should be applied. Only one + `google_gke_hub_membership_iam_binding` can be used per role. Note that custom roles must be of the format + `[projects|organizations]/{parent-name}/roles/{role-name}`. + +* `policy_data` - (Required only by `google_gke_hub_membership_iam_policy`) The policy data generated by + a `google_iam_policy` data source. + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are +exported: + +* `etag` - (Computed) The etag of the IAM policy. + +## Import + +For all import syntaxes, the "resource in question" can take any of the following forms: + +* projects/{{project}}/locations/{{location}}/memberships/{{membership_id}} +* {{project}}/{{location}}/{{membership_id}} +* {{location}}/{{membership_id}} +* {{membership_id}} + +Any variables not passed in the import command will be taken from the provider configuration. + +GKEHub membership IAM resources can be imported using the resource identifiers, role, and member. + +IAM member imports use space-delimited identifiers: the resource in question, the role, and the member identity, e.g. +``` +$ terraform import google_gke_hub_membership_iam_member.editor "projects/{{project}}/locations/{{location}}/memberships/{{membership_id}} roles/viewer user:jane@example.com" +``` + +IAM binding imports use space-delimited identifiers: the resource in question and the role, e.g. +``` +$ terraform import google_gke_hub_membership_iam_binding.editor "projects/{{project}}/locations/{{location}}/memberships/{{membership_id}} roles/viewer" +``` + +IAM policy imports use the identifier of the resource in question, e.g. +``` +$ terraform import google_gke_hub_membership_iam_policy.editor projects/{{project}}/locations/{{location}}/memberships/{{membership_id}} +``` + +-> **Custom Roles**: If you're importing a IAM resource with a custom role, make sure to use the + full name of the custom role, e.g. `[projects/my-project|organizations/my-org]/roles/my-custom-role`. + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override).