From e8dbbbd39acf7356d9da7392df40172599e4059e Mon Sep 17 00:00:00 2001 From: The Magician Date: Wed, 6 Jul 2022 07:56:55 -0700 Subject: [PATCH] snapshot iam (#6194) (#4445) Signed-off-by: Modular Magician --- .changelog/6194.txt | 9 + google-beta/iam_compute_snapshot.go | 198 ++++++++++++ .../iam_compute_snapshot_generated_test.go | 295 ++++++++++++++++++ google-beta/provider.go | 7 +- .../docs/r/compute_snapshot_iam.html.markdown | 147 +++++++++ website/google.erb | 4 + 6 files changed, 658 insertions(+), 2 deletions(-) create mode 100644 .changelog/6194.txt create mode 100644 google-beta/iam_compute_snapshot.go create mode 100644 google-beta/iam_compute_snapshot_generated_test.go create mode 100644 website/docs/r/compute_snapshot_iam.html.markdown diff --git a/.changelog/6194.txt b/.changelog/6194.txt new file mode 100644 index 0000000000..d3fe0c10b1 --- /dev/null +++ b/.changelog/6194.txt @@ -0,0 +1,9 @@ +```release-note:new-resource +google_compute_snapshot_iam_member +``` +```release-note:new-resource +google_compute_snapshot_iam_binding +``` +```release-note:new-resource +google_compute_snapshot_iam_policy +``` diff --git a/google-beta/iam_compute_snapshot.go b/google-beta/iam_compute_snapshot.go new file mode 100644 index 0000000000..8e658ae034 --- /dev/null +++ b/google-beta/iam_compute_snapshot.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 ComputeSnapshotIamSchema = map[string]*schema.Schema{ + "project": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + }, +} + +type ComputeSnapshotIamUpdater struct { + project string + name string + d TerraformResourceData + Config *Config +} + +func ComputeSnapshotIamUpdaterProducer(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("name"); ok { + values["name"] = 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[^/]+)/global/snapshots/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Get("name").(string)) + if err != nil { + return nil, err + } + + for k, v := range m { + values[k] = v + } + + u := &ComputeSnapshotIamUpdater{ + project: values["project"], + name: values["name"], + 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("name", u.GetResourceId()); err != nil { + return nil, fmt.Errorf("Error setting name: %s", err) + } + + return u, nil +} + +func ComputeSnapshotIdParseFunc(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[^/]+)/global/snapshots/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Id()) + if err != nil { + return err + } + + for k, v := range m { + values[k] = v + } + + u := &ComputeSnapshotIamUpdater{ + project: values["project"], + name: values["name"], + d: d, + Config: config, + } + if err := d.Set("name", u.GetResourceId()); err != nil { + return fmt.Errorf("Error setting name: %s", err) + } + d.SetId(u.GetResourceId()) + return nil +} + +func (u *ComputeSnapshotIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { + url, err := u.qualifySnapshotUrl("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 *ComputeSnapshotIamUpdater) 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.qualifySnapshotUrl("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 *ComputeSnapshotIamUpdater) qualifySnapshotUrl(methodIdentifier string) (string, error) { + urlTemplate := fmt.Sprintf("{{ComputeBasePath}}%s/%s", fmt.Sprintf("projects/%s/global/snapshots/%s", u.project, u.name), methodIdentifier) + url, err := replaceVars(u.d, u.Config, urlTemplate) + if err != nil { + return "", err + } + return url, nil +} + +func (u *ComputeSnapshotIamUpdater) GetResourceId() string { + return fmt.Sprintf("projects/%s/global/snapshots/%s", u.project, u.name) +} + +func (u *ComputeSnapshotIamUpdater) GetMutexKey() string { + return fmt.Sprintf("iam-compute-snapshot-%s", u.GetResourceId()) +} + +func (u *ComputeSnapshotIamUpdater) DescribeResource() string { + return fmt.Sprintf("compute snapshot %q", u.GetResourceId()) +} diff --git a/google-beta/iam_compute_snapshot_generated_test.go b/google-beta/iam_compute_snapshot_generated_test.go new file mode 100644 index 0000000000..46649e1cd7 --- /dev/null +++ b/google-beta/iam_compute_snapshot_generated_test.go @@ -0,0 +1,295 @@ +// ---------------------------------------------------------------------------- +// +// *** 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 TestAccComputeSnapshotIamBindingGenerated(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: testAccComputeSnapshotIamBinding_basicGenerated(context), + }, + { + ResourceName: "google_compute_snapshot_iam_binding.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/snapshots/%s roles/viewer", getTestProjectFromEnv(), fmt.Sprintf("tf-test-my-snapshot%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + { + // Test Iam Binding update + Config: testAccComputeSnapshotIamBinding_updateGenerated(context), + }, + { + ResourceName: "google_compute_snapshot_iam_binding.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/snapshots/%s roles/viewer", getTestProjectFromEnv(), fmt.Sprintf("tf-test-my-snapshot%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeSnapshotIamMemberGenerated(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: testAccComputeSnapshotIamMember_basicGenerated(context), + }, + { + ResourceName: "google_compute_snapshot_iam_member.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/snapshots/%s roles/viewer user:admin@hashicorptest.com", getTestProjectFromEnv(), fmt.Sprintf("tf-test-my-snapshot%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeSnapshotIamPolicyGenerated(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: testAccComputeSnapshotIamPolicy_basicGenerated(context), + }, + { + ResourceName: "google_compute_snapshot_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/snapshots/%s", getTestProjectFromEnv(), fmt.Sprintf("tf-test-my-snapshot%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeSnapshotIamPolicy_emptyBinding(context), + }, + { + ResourceName: "google_compute_snapshot_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/snapshots/%s", getTestProjectFromEnv(), fmt.Sprintf("tf-test-my-snapshot%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccComputeSnapshotIamMember_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_snapshot" "snapshot" { + name = "tf-test-my-snapshot%{random_suffix}" + source_disk = google_compute_disk.persistent.id + zone = "us-central1-a" + labels = { + my_label = "value" + } + storage_locations = ["us-central1"] +} + +data "google_compute_image" "debian" { + family = "debian-9" + project = "debian-cloud" +} + +resource "google_compute_disk" "persistent" { + name = "tf-test-debian-disk%{random_suffix}" + image = data.google_compute_image.debian.self_link + size = 10 + type = "pd-ssd" + zone = "us-central1-a" +} + +resource "google_compute_snapshot_iam_member" "foo" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + role = "%{role}" + member = "user:admin@hashicorptest.com" +} +`, context) +} + +func testAccComputeSnapshotIamPolicy_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_snapshot" "snapshot" { + name = "tf-test-my-snapshot%{random_suffix}" + source_disk = google_compute_disk.persistent.id + zone = "us-central1-a" + labels = { + my_label = "value" + } + storage_locations = ["us-central1"] +} + +data "google_compute_image" "debian" { + family = "debian-9" + project = "debian-cloud" +} + +resource "google_compute_disk" "persistent" { + name = "tf-test-debian-disk%{random_suffix}" + image = data.google_compute_image.debian.self_link + size = 10 + type = "pd-ssd" + zone = "us-central1-a" +} + +data "google_iam_policy" "foo" { + binding { + role = "%{role}" + members = ["user:admin@hashicorptest.com"] + } +} + +resource "google_compute_snapshot_iam_policy" "foo" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccComputeSnapshotIamPolicy_emptyBinding(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_snapshot" "snapshot" { + name = "tf-test-my-snapshot%{random_suffix}" + source_disk = google_compute_disk.persistent.id + zone = "us-central1-a" + labels = { + my_label = "value" + } + storage_locations = ["us-central1"] +} + +data "google_compute_image" "debian" { + family = "debian-9" + project = "debian-cloud" +} + +resource "google_compute_disk" "persistent" { + name = "tf-test-debian-disk%{random_suffix}" + image = data.google_compute_image.debian.self_link + size = 10 + type = "pd-ssd" + zone = "us-central1-a" +} + +data "google_iam_policy" "foo" { +} + +resource "google_compute_snapshot_iam_policy" "foo" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccComputeSnapshotIamBinding_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_snapshot" "snapshot" { + name = "tf-test-my-snapshot%{random_suffix}" + source_disk = google_compute_disk.persistent.id + zone = "us-central1-a" + labels = { + my_label = "value" + } + storage_locations = ["us-central1"] +} + +data "google_compute_image" "debian" { + family = "debian-9" + project = "debian-cloud" +} + +resource "google_compute_disk" "persistent" { + name = "tf-test-debian-disk%{random_suffix}" + image = data.google_compute_image.debian.self_link + size = 10 + type = "pd-ssd" + zone = "us-central1-a" +} + +resource "google_compute_snapshot_iam_binding" "foo" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + role = "%{role}" + members = ["user:admin@hashicorptest.com"] +} +`, context) +} + +func testAccComputeSnapshotIamBinding_updateGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_snapshot" "snapshot" { + name = "tf-test-my-snapshot%{random_suffix}" + source_disk = google_compute_disk.persistent.id + zone = "us-central1-a" + labels = { + my_label = "value" + } + storage_locations = ["us-central1"] +} + +data "google_compute_image" "debian" { + family = "debian-9" + project = "debian-cloud" +} + +resource "google_compute_disk" "persistent" { + name = "tf-test-debian-disk%{random_suffix}" + image = data.google_compute_image.debian.self_link + size = 10 + type = "pd-ssd" + zone = "us-central1-a" +} + +resource "google_compute_snapshot_iam_binding" "foo" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + role = "%{role}" + members = ["user:admin@hashicorptest.com", "user:gterraformtest1@gmail.com"] +} +`, context) +} diff --git a/google-beta/provider.go b/google-beta/provider.go index 9ad6814087..0e9832d143 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -936,8 +936,8 @@ func Provider() *schema.Provider { } // Generated resources: 252 -// Generated IAM resources: 153 -// Total generated resources: 405 +// Generated IAM resources: 156 +// Total generated resources: 408 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -1109,6 +1109,9 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_compute_router_nat": resourceComputeRouterNat(), "google_compute_router_peer": resourceComputeRouterBgpPeer(), "google_compute_snapshot": resourceComputeSnapshot(), + "google_compute_snapshot_iam_binding": ResourceIamBinding(ComputeSnapshotIamSchema, ComputeSnapshotIamUpdaterProducer, ComputeSnapshotIdParseFunc), + "google_compute_snapshot_iam_member": ResourceIamMember(ComputeSnapshotIamSchema, ComputeSnapshotIamUpdaterProducer, ComputeSnapshotIdParseFunc), + "google_compute_snapshot_iam_policy": ResourceIamPolicy(ComputeSnapshotIamSchema, ComputeSnapshotIamUpdaterProducer, ComputeSnapshotIdParseFunc), "google_compute_ssl_certificate": resourceComputeSslCertificate(), "google_compute_managed_ssl_certificate": resourceComputeManagedSslCertificate(), "google_compute_region_ssl_certificate": resourceComputeRegionSslCertificate(), diff --git a/website/docs/r/compute_snapshot_iam.html.markdown b/website/docs/r/compute_snapshot_iam.html.markdown new file mode 100644 index 0000000000..db7171d82e --- /dev/null +++ b/website/docs/r/compute_snapshot_iam.html.markdown @@ -0,0 +1,147 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Compute Engine" +layout: "google" +page_title: "Google: google_compute_snapshot_iam" +sidebar_current: "docs-google-compute-snapshot-iam" +description: |- + Collection of resources to manage IAM policy for Compute Engine Snapshot +--- + +# IAM policy for Compute Engine Snapshot +Three different resources help you manage your IAM policy for Compute Engine Snapshot. Each of these resources serves a different use case: + +* `google_compute_snapshot_iam_policy`: Authoritative. Sets the IAM policy for the snapshot and replaces any existing policy already attached. +* `google_compute_snapshot_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 snapshot are preserved. +* `google_compute_snapshot_iam_member`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the snapshot are preserved. + +~> **Note:** `google_compute_snapshot_iam_policy` **cannot** be used in conjunction with `google_compute_snapshot_iam_binding` and `google_compute_snapshot_iam_member` or they will fight over what your policy should be. + +~> **Note:** `google_compute_snapshot_iam_binding` resources **can be** used in conjunction with `google_compute_snapshot_iam_member` resources **only if** they do not grant privilege to the same role. + + + + +## google\_compute\_snapshot\_iam\_policy + +```hcl +data "google_iam_policy" "admin" { + binding { + role = "roles/viewer" + members = [ + "user:jane@example.com", + ] + } +} + +resource "google_compute_snapshot_iam_policy" "policy" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + policy_data = data.google_iam_policy.admin.policy_data +} +``` + +## google\_compute\_snapshot\_iam\_binding + +```hcl +resource "google_compute_snapshot_iam_binding" "binding" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + role = "roles/viewer" + members = [ + "user:jane@example.com", + ] +} +``` + +## google\_compute\_snapshot\_iam\_member + +```hcl +resource "google_compute_snapshot_iam_member" "member" { + project = google_compute_snapshot.snapshot.project + name = google_compute_snapshot.snapshot.name + role = "roles/viewer" + member = "user:jane@example.com" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Used to find the parent resource to bind the IAM policy to + +* `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_compute_snapshot_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_compute_snapshot_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}}/global/snapshots/{{name}} +* {{project}}/{{name}} +* {{name}} + +Any variables not passed in the import command will be taken from the provider configuration. + +Compute Engine snapshot 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_compute_snapshot_iam_member.editor "projects/{{project}}/global/snapshots/{{snapshot}} 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_compute_snapshot_iam_binding.editor "projects/{{project}}/global/snapshots/{{snapshot}} roles/viewer" +``` + +IAM policy imports use the identifier of the resource in question, e.g. +``` +$ terraform import google_compute_snapshot_iam_policy.editor projects/{{project}}/global/snapshots/{{snapshot}} +``` + +-> **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). diff --git a/website/google.erb b/website/google.erb index f8e2aba601..a1c26d8446 100644 --- a/website/google.erb +++ b/website/google.erb @@ -2223,6 +2223,10 @@ google_compute_snapshot +
  • + google_compute_snapshot_iam +
  • +
  • google_compute_ssl_certificate