From 09801c60d18718036db7840a0a652538d4c9480a Mon Sep 17 00:00:00 2001 From: The Magician Date: Thu, 20 Aug 2020 06:53:34 -0700 Subject: [PATCH] add support for iam resources for google_compute_image (#3887) (#7070) Signed-off-by: Modular Magician --- .changelog/3887.txt | 9 + google/iam_compute_image.go | 184 +++++++++++++++ google/iam_compute_image_generated_test.go | 220 ++++++++++++++++++ google/provider.go | 7 +- .../docs/r/compute_image_iam.html.markdown | 146 ++++++++++++ website/google.erb | 4 + 6 files changed, 568 insertions(+), 2 deletions(-) create mode 100644 .changelog/3887.txt create mode 100644 google/iam_compute_image.go create mode 100644 google/iam_compute_image_generated_test.go create mode 100644 website/docs/r/compute_image_iam.html.markdown diff --git a/.changelog/3887.txt b/.changelog/3887.txt new file mode 100644 index 00000000000..a605ae37aeb --- /dev/null +++ b/.changelog/3887.txt @@ -0,0 +1,9 @@ +```release-note:new-resource +`google_compute_image_iam_binding` +``` +```release-note:new-resource +`google_compute_image_iam_member` +``` +```release-note:new-resource +`google_compute_image_iam_policy` +``` diff --git a/google/iam_compute_image.go b/google/iam_compute_image.go new file mode 100644 index 00000000000..8cf39f4b018 --- /dev/null +++ b/google/iam_compute_image.go @@ -0,0 +1,184 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "google.golang.org/api/cloudresourcemanager/v1" +) + +var ComputeImageIamSchema = map[string]*schema.Schema{ + "project": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + }, + "image": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + }, +} + +type ComputeImageIamUpdater struct { + project string + image string + d *schema.ResourceData + Config *Config +} + +func ComputeImageIamUpdaterProducer(d *schema.ResourceData, config *Config) (ResourceIamUpdater, error) { + values := make(map[string]string) + + project, _ := getProject(d, config) + if project != "" { + d.Set("project", project) + } + values["project"] = project + if v, ok := d.GetOk("image"); ok { + values["image"] = 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/images/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Get("image").(string)) + if err != nil { + return nil, err + } + + for k, v := range m { + values[k] = v + } + + u := &ComputeImageIamUpdater{ + project: values["project"], + image: values["image"], + d: d, + Config: config, + } + + d.Set("project", u.project) + d.Set("image", u.GetResourceId()) + + return u, nil +} + +func ComputeImageIdParseFunc(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/images/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Id()) + if err != nil { + return err + } + + for k, v := range m { + values[k] = v + } + + u := &ComputeImageIamUpdater{ + project: values["project"], + image: values["image"], + d: d, + Config: config, + } + d.Set("image", u.GetResourceId()) + d.SetId(u.GetResourceId()) + return nil +} + +func (u *ComputeImageIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { + url, err := u.qualifyImageUrl("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{} + url, err = addQueryParams(url, map[string]string{"optionsRequestedPolicyVersion": fmt.Sprintf("%d", iamPolicyVersion)}) + if err != nil { + return nil, err + } + + policy, err := sendRequest(u.Config, "GET", project, url, 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 *ComputeImageIamUpdater) 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.qualifyImageUrl("setIamPolicy") + if err != nil { + return err + } + project, err := getProject(u.d, u.Config) + if err != nil { + return err + } + + _, err = sendRequestWithTimeout(u.Config, "POST", project, url, 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 *ComputeImageIamUpdater) qualifyImageUrl(methodIdentifier string) (string, error) { + urlTemplate := fmt.Sprintf("{{ComputeBasePath}}%s/%s", fmt.Sprintf("projects/%s/global/images/%s", u.project, u.image), methodIdentifier) + url, err := replaceVars(u.d, u.Config, urlTemplate) + if err != nil { + return "", err + } + return url, nil +} + +func (u *ComputeImageIamUpdater) GetResourceId() string { + return fmt.Sprintf("projects/%s/global/images/%s", u.project, u.image) +} + +func (u *ComputeImageIamUpdater) GetMutexKey() string { + return fmt.Sprintf("iam-compute-image-%s", u.GetResourceId()) +} + +func (u *ComputeImageIamUpdater) DescribeResource() string { + return fmt.Sprintf("compute image %q", u.GetResourceId()) +} diff --git a/google/iam_compute_image_generated_test.go b/google/iam_compute_image_generated_test.go new file mode 100644 index 00000000000..c84b2c56c6f --- /dev/null +++ b/google/iam_compute_image_generated_test.go @@ -0,0 +1,220 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func TestAccComputeImageIamBindingGenerated(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/compute.imageUser", + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccComputeImageIamBinding_basicGenerated(context), + }, + { + ResourceName: "google_compute_image_iam_binding.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/images/%s roles/compute.imageUser", getTestProjectFromEnv(), fmt.Sprintf("tf-test-example-image%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + { + // Test Iam Binding update + Config: testAccComputeImageIamBinding_updateGenerated(context), + }, + { + ResourceName: "google_compute_image_iam_binding.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/images/%s roles/compute.imageUser", getTestProjectFromEnv(), fmt.Sprintf("tf-test-example-image%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeImageIamMemberGenerated(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/compute.imageUser", + } + + 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: testAccComputeImageIamMember_basicGenerated(context), + }, + { + ResourceName: "google_compute_image_iam_member.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/images/%s roles/compute.imageUser user:admin@hashicorptest.com", getTestProjectFromEnv(), fmt.Sprintf("tf-test-example-image%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeImageIamPolicyGenerated(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/compute.imageUser", + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccComputeImageIamPolicy_basicGenerated(context), + }, + { + ResourceName: "google_compute_image_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/images/%s", getTestProjectFromEnv(), fmt.Sprintf("tf-test-example-image%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeImageIamPolicy_emptyBinding(context), + }, + { + ResourceName: "google_compute_image_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/global/images/%s", getTestProjectFromEnv(), fmt.Sprintf("tf-test-example-image%s", context["random_suffix"])), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccComputeImageIamMember_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_image" "example" { + name = "tf-test-example-image%{random_suffix}" + + raw_disk { + source = "https://storage.googleapis.com/bosh-cpi-artifacts/bosh-stemcell-3262.4-google-kvm-ubuntu-trusty-go_agent-raw.tar.gz" + } +} + +resource "google_compute_image_iam_member" "foo" { + project = google_compute_image.example.project + image = google_compute_image.example.name + role = "%{role}" + member = "user:admin@hashicorptest.com" +} +`, context) +} + +func testAccComputeImageIamPolicy_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_image" "example" { + name = "tf-test-example-image%{random_suffix}" + + raw_disk { + source = "https://storage.googleapis.com/bosh-cpi-artifacts/bosh-stemcell-3262.4-google-kvm-ubuntu-trusty-go_agent-raw.tar.gz" + } +} + +data "google_iam_policy" "foo" { + binding { + role = "%{role}" + members = ["user:admin@hashicorptest.com"] + } +} + +resource "google_compute_image_iam_policy" "foo" { + project = google_compute_image.example.project + image = google_compute_image.example.name + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccComputeImageIamPolicy_emptyBinding(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_image" "example" { + name = "tf-test-example-image%{random_suffix}" + + raw_disk { + source = "https://storage.googleapis.com/bosh-cpi-artifacts/bosh-stemcell-3262.4-google-kvm-ubuntu-trusty-go_agent-raw.tar.gz" + } +} + +data "google_iam_policy" "foo" { +} + +resource "google_compute_image_iam_policy" "foo" { + project = google_compute_image.example.project + image = google_compute_image.example.name + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccComputeImageIamBinding_basicGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_image" "example" { + name = "tf-test-example-image%{random_suffix}" + + raw_disk { + source = "https://storage.googleapis.com/bosh-cpi-artifacts/bosh-stemcell-3262.4-google-kvm-ubuntu-trusty-go_agent-raw.tar.gz" + } +} + +resource "google_compute_image_iam_binding" "foo" { + project = google_compute_image.example.project + image = google_compute_image.example.name + role = "%{role}" + members = ["user:admin@hashicorptest.com"] +} +`, context) +} + +func testAccComputeImageIamBinding_updateGenerated(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_image" "example" { + name = "tf-test-example-image%{random_suffix}" + + raw_disk { + source = "https://storage.googleapis.com/bosh-cpi-artifacts/bosh-stemcell-3262.4-google-kvm-ubuntu-trusty-go_agent-raw.tar.gz" + } +} + +resource "google_compute_image_iam_binding" "foo" { + project = google_compute_image.example.project + image = google_compute_image.example.name + role = "%{role}" + members = ["user:admin@hashicorptest.com", "user:paddy@hashicorp.com"] +} +`, context) +} diff --git a/google/provider.go b/google/provider.go index c7ae525862c..cfac4198db6 100644 --- a/google/provider.go +++ b/google/provider.go @@ -616,8 +616,8 @@ func Provider() terraform.ResourceProvider { } // Generated resources: 155 -// Generated IAM resources: 60 -// Total generated resources: 215 +// Generated IAM resources: 63 +// Total generated resources: 218 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -690,6 +690,9 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_compute_https_health_check": resourceComputeHttpsHealthCheck(), "google_compute_health_check": resourceComputeHealthCheck(), "google_compute_image": resourceComputeImage(), + "google_compute_image_iam_binding": ResourceIamBinding(ComputeImageIamSchema, ComputeImageIamUpdaterProducer, ComputeImageIdParseFunc), + "google_compute_image_iam_member": ResourceIamMember(ComputeImageIamSchema, ComputeImageIamUpdaterProducer, ComputeImageIdParseFunc), + "google_compute_image_iam_policy": ResourceIamPolicy(ComputeImageIamSchema, ComputeImageIamUpdaterProducer, ComputeImageIdParseFunc), "google_compute_instance_iam_binding": ResourceIamBinding(ComputeInstanceIamSchema, ComputeInstanceIamUpdaterProducer, ComputeInstanceIdParseFunc), "google_compute_instance_iam_member": ResourceIamMember(ComputeInstanceIamSchema, ComputeInstanceIamUpdaterProducer, ComputeInstanceIdParseFunc), "google_compute_instance_iam_policy": ResourceIamPolicy(ComputeInstanceIamSchema, ComputeInstanceIamUpdaterProducer, ComputeInstanceIdParseFunc), diff --git a/website/docs/r/compute_image_iam.html.markdown b/website/docs/r/compute_image_iam.html.markdown new file mode 100644 index 00000000000..ba26e3ee855 --- /dev/null +++ b/website/docs/r/compute_image_iam.html.markdown @@ -0,0 +1,146 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Compute Engine" +layout: "google" +page_title: "Google: google_compute_image_iam" +sidebar_current: "docs-google-compute-image-iam" +description: |- + Collection of resources to manage IAM policy for Compute Engine Image +--- + +# IAM policy for Compute Engine Image +Three different resources help you manage your IAM policy for Compute Engine Image. Each of these resources serves a different use case: + +* `google_compute_image_iam_policy`: Authoritative. Sets the IAM policy for the image and replaces any existing policy already attached. +* `google_compute_image_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 image are preserved. +* `google_compute_image_iam_member`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the image are preserved. + +~> **Note:** `google_compute_image_iam_policy` **cannot** be used in conjunction with `google_compute_image_iam_binding` and `google_compute_image_iam_member` or they will fight over what your policy should be. + +~> **Note:** `google_compute_image_iam_binding` resources **can be** used in conjunction with `google_compute_image_iam_member` resources **only if** they do not grant privilege to the same role. + + + +## google\_compute\_image\_iam\_policy + +```hcl +data "google_iam_policy" "admin" { + binding { + role = "roles/compute.imageUser" + members = [ + "user:jane@example.com", + ] + } +} + +resource "google_compute_image_iam_policy" "policy" { + project = google_compute_image.example.project + image = google_compute_image.example.name + policy_data = data.google_iam_policy.admin.policy_data +} +``` + +## google\_compute\_image\_iam\_binding + +```hcl +resource "google_compute_image_iam_binding" "binding" { + project = google_compute_image.example.project + image = google_compute_image.example.name + role = "roles/compute.imageUser" + members = [ + "user:jane@example.com", + ] +} +``` + +## google\_compute\_image\_iam\_member + +```hcl +resource "google_compute_image_iam_member" "member" { + project = google_compute_image.example.project + image = google_compute_image.example.name + role = "roles/compute.imageUser" + member = "user:jane@example.com" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `image` - (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. + +* `role` - (Required) The role that should be applied. Only one + `google_compute_image_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_image_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/images/{{name}} +* {{project}}/{{name}} +* {{name}} + +Any variables not passed in the import command will be taken from the provider configuration. + +Compute Engine image 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_image_iam_member.editor "projects/{{project}}/global/images/{{image}} roles/compute.imageUser user:jane@example.com" +``` + +IAM binding imports use space-delimited identifiers: the resource in question and the role, e.g. +``` +$ terraform import google_compute_image_iam_binding.editor "projects/{{project}}/global/images/{{image}} roles/compute.imageUser" +``` + +IAM policy imports use the identifier of the resource in question, e.g. +``` +$ terraform import google_compute_image_iam_policy.editor projects/{{project}}/global/images/{{image}} +``` + +-> If you're importing a resource with beta features, make sure to include `-provider=google-beta` +as an argument so that Terraform uses the correct provider to import your resource. + +-> **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 3601e9c5b79..c17047f2702 100644 --- a/website/google.erb +++ b/website/google.erb @@ -1321,6 +1321,10 @@ google_compute_image +
  • + google_compute_image_iam +
  • +
  • google_compute_instance