diff --git a/google-beta/config.go b/google-beta/config.go index 4884a489149..a91b6a3373b 100644 --- a/google-beta/config.go +++ b/google-beta/config.go @@ -35,6 +35,7 @@ import ( file "google.golang.org/api/file/v1beta1" "google.golang.org/api/iam/v1" iamcredentials "google.golang.org/api/iamcredentials/v1" + iap "google.golang.org/api/iap/v1beta1" cloudlogging "google.golang.org/api/logging/v2" "google.golang.org/api/option" "google.golang.org/api/pubsub/v1" @@ -88,6 +89,7 @@ type Config struct { clientStorage *storage.Service clientSqlAdmin *sqladmin.Service clientIAM *iam.Service + clientIAP *iap.Service clientServiceMan *servicemanagement.APIService clientServiceUsage *serviceusage.Service clientBigQuery *bigquery.Service @@ -254,6 +256,13 @@ func (c *Config) LoadAndValidate() error { } c.clientIamCredentials.UserAgent = userAgent + log.Printf("[INFO] Instantiating IAP Client...") + c.clientIAP, err = iap.NewService(context, option.WithHTTPClient(client)) + if err != nil { + return err + } + c.clientIAP.UserAgent = userAgent + log.Printf("[INFO] Instantiating Google Cloud Service Management Client...") c.clientServiceMan, err = servicemanagement.NewService(context, option.WithHTTPClient(client)) if err != nil { diff --git a/google-beta/iam_iap_tunnel_instance.go b/google-beta/iam_iap_tunnel_instance.go new file mode 100644 index 00000000000..3b246a6080e --- /dev/null +++ b/google-beta/iam_iap_tunnel_instance.go @@ -0,0 +1,189 @@ +package google + +import ( + "fmt" + "strconv" + "strings" + + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/schema" + "google.golang.org/api/cloudresourcemanager/v1" + iap "google.golang.org/api/iap/v1beta1" +) + +var IamIapTunnelInstanceSchema = map[string]*schema.Schema{ + "instance": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "zone": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, +} + +type IapTunnelInstanceIamUpdater struct { + project string + zone string + instance string + projectNumber string + Config *Config +} + +func NewIapTunnelInstanceIamUpdater(d *schema.ResourceData, config *Config) (ResourceIamUpdater, error) { + project, err := getProject(d, config) + if err != nil { + return nil, err + } + + res, err := config.clientResourceManager.Projects.Get(project).Do() + if err != nil { + return nil, err + } + + //The IAP API currently doesn't work when using a projectId. When hitting the endpoint with a projectId instead + //of a projectNumber, the backend returns a 400 error, saying that it is an invalid argument. We abstract away + //this implementation detail from the consumer, and allow consumers to work with projectIds, which is consistent + //with other resources. However, that means we have to maintain/lookup the projectNumber from the projectID + //inside this provider plugin. + projectNumber := strconv.FormatInt(res.ProjectNumber, 10) + + zone, err := getZone(d, config) + if err != nil { + return nil, err + } + + return &IapTunnelInstanceIamUpdater{ + project: project, + projectNumber: projectNumber, + zone: zone, + instance: d.Get("instance").(string), + Config: config, + }, nil +} + +func IapTunnelInstanceIdParseFunc(d *schema.ResourceData, config *Config) error { + parts := strings.Split(d.Id(), "/") + var fv *ZonalFieldValue + if len(parts) == 3 { + // {project}/{zone}/{name} syntax + fv = &ZonalFieldValue{ + Project: parts[0], + Zone: parts[1], + Name: parts[2], + resourceType: "instances", + } + } else if len(parts) == 2 { + // /{zone}/{name} syntax + project, err := getProject(d, config) + if err != nil { + return err + } + fv = &ZonalFieldValue{ + Project: project, + Zone: parts[0], + Name: parts[1], + resourceType: "instances", + } + } else { + // We either have a name or a full self link, so use the field helper + var err error + fv, err = ParseInstanceFieldValue(d.Id(), d, config) + if err != nil { + return err + } + } + + d.Set("project", fv.Project) + d.Set("zone", fv.Zone) + d.Set("instance", fv.Name) + + res, err := config.clientResourceManager.Projects.Get(fv.Project).Do() + if err != nil { + return err + } + + projectNumber := strconv.FormatInt(res.ProjectNumber, 10) + + // Explicitly set the id so imported resources have the same ID format as non-imported ones. + d.SetId(fmt.Sprintf("projects/%s/iap_tunnel/zones/%s/instances/%s", projectNumber, fv.Zone, fv.Name)) + return nil +} + +func (u *IapTunnelInstanceIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { + req := &iap.GetIamPolicyRequest{} + + p, err := u.Config.clientIAP.V1beta1.GetIamPolicy(fmt.Sprintf("projects/%s/iap_tunnel/zones/%s/instances/%s", u.projectNumber, u.zone, u.instance), req).Do() + + if err != nil { + return nil, errwrap.Wrapf(fmt.Sprintf("Error retrieving IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + cloudResourcePolicy, err := iapToResourceManagerPolicy(p) + + if err != nil { + return nil, errwrap.Wrapf(fmt.Sprintf("Invalid IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + return cloudResourcePolicy, nil +} + +func (u *IapTunnelInstanceIamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error { + iapPolicy, err := resourceManagerToIapPolicy(policy) + + if err != nil { + return errwrap.Wrapf(fmt.Sprintf("Invalid IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + req := &iap.SetIamPolicyRequest{ + Policy: iapPolicy, + } + _, err = u.Config.clientIAP.V1beta1.SetIamPolicy(fmt.Sprintf("projects/%s/iap_tunnel/zones/%s/instances/%s", u.projectNumber, u.zone, u.instance), req).Do() + + if err != nil { + return errwrap.Wrapf(fmt.Sprintf("Error setting IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + return nil +} + +func (u *IapTunnelInstanceIamUpdater) GetResourceId() string { + return fmt.Sprintf("projects/%s/iap_tunnel/zones/%s/instances/%s", u.projectNumber, u.zone, u.instance) +} + +func (u *IapTunnelInstanceIamUpdater) GetMutexKey() string { + return fmt.Sprintf("iap-tunnel-instance-%s-%s-%s", u.projectNumber, u.zone, u.instance) +} + +func (u *IapTunnelInstanceIamUpdater) DescribeResource() string { + return fmt.Sprintf("IAP Tunnel Instance %s/%s/%s", u.projectNumber, u.zone, u.instance) +} + +func resourceManagerToIapPolicy(p *cloudresourcemanager.Policy) (*iap.Policy, error) { + out := &iap.Policy{} + err := Convert(p, out) + if err != nil { + return nil, errwrap.Wrapf("Cannot convert a resourcemanager policy to am IAP policy: {{err}}", err) + } + return out, nil +} + +func iapToResourceManagerPolicy(p *iap.Policy) (*cloudresourcemanager.Policy, error) { + out := &cloudresourcemanager.Policy{} + err := Convert(p, out) + if err != nil { + return nil, errwrap.Wrapf("Cannot convert an IAP policy to a resourcemanager policy: {{err}}", err) + } + return out, nil +} diff --git a/google-beta/provider.go b/google-beta/provider.go index 2706b85a001..ba753995a12 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -208,6 +208,9 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_folder_iam_member": ResourceIamMemberWithImport(IamFolderSchema, NewFolderIamUpdater, FolderIdParseFunc), "google_folder_iam_policy": ResourceIamPolicyWithImport(IamFolderSchema, NewFolderIamUpdater, FolderIdParseFunc), "google_folder_organization_policy": resourceGoogleFolderOrganizationPolicy(), + "google_iap_tunnel_instance_iam_binding": ResourceIamBindingWithImport(IamIapTunnelInstanceSchema, NewIapTunnelInstanceIamUpdater, IapTunnelInstanceIdParseFunc), + "google_iap_tunnel_instance_iam_member": ResourceIamMemberWithImport(IamIapTunnelInstanceSchema, NewIapTunnelInstanceIamUpdater, IapTunnelInstanceIdParseFunc), + "google_iap_tunnel_instance_iam_policy": ResourceIamPolicyWithImport(IamIapTunnelInstanceSchema, NewIapTunnelInstanceIamUpdater, IapTunnelInstanceIdParseFunc), "google_logging_billing_account_sink": resourceLoggingBillingAccountSink(), "google_logging_billing_account_exclusion": ResourceLoggingExclusion(BillingAccountLoggingExclusionSchema, NewBillingAccountLoggingExclusionUpdater, billingAccountLoggingExclusionIdParseFunc), "google_logging_metric": resourceLoggingMetric(), diff --git a/google-beta/resource_iap_tunnel_instance_iam_test.go b/google-beta/resource_iap_tunnel_instance_iam_test.go new file mode 100644 index 00000000000..44ab730bb06 --- /dev/null +++ b/google-beta/resource_iap_tunnel_instance_iam_test.go @@ -0,0 +1,218 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccIapTunnelInstanceIamBinding(t *testing.T) { + t.Parallel() + + project := getTestProjectFromEnv() + zone := getTestZoneFromEnv() + instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccIapTunnelInstanceIamBinding_basic(zone, instanceName), + }, + { + ResourceName: "google_iap_tunnel_instance_iam_binding.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s roles/iap.tunnelResourceAccessor", project, zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + { + // Test Iam Binding update + Config: testAccIapTunnelInstanceIamBinding_update(zone, instanceName), + }, + { + ResourceName: "google_iap_tunnel_instance_iam_binding.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s roles/iap.tunnelResourceAccessor", project, zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccIapTunnelInstanceIamMember(t *testing.T) { + t.Parallel() + + project := getTestProjectFromEnv() + zone := getTestZoneFromEnv() + instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(10)) + + resource.Test(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: testAccIapTunnelInstanceIamMember_basic(zone, instanceName), + }, + { + ResourceName: "google_iap_tunnel_instance_iam_member.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s roles/iap.tunnelResourceAccessor user:admin@hashicorptest.com", project, zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccIapTunnelInstanceIamPolicy(t *testing.T) { + t.Parallel() + + project := getTestProjectFromEnv() + zone := getTestZoneFromEnv() + instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccIapTunnelInstanceIamPolicy_basic(zone, instanceName), + }, + // Test a few import formats + { + ResourceName: "google_iap_tunnel_instance_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/zones/%s/instances/%s", project, zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + { + ResourceName: "google_iap_tunnel_instance_iam_policy.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s", project, zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + { + ResourceName: "google_iap_tunnel_instance_iam_policy.foo", + ImportStateId: fmt.Sprintf("%s/%s", zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccIapTunnelInstanceIamBinding_basic(zone, instanceName string) string { + return fmt.Sprintf(` +resource "google_compute_instance" "test_vm" { + zone = "%s" + name = "%s" + machine_type = "n1-standard-1" + boot_disk { + initialize_params { + image = "debian-cloud/debian-9" + } + } + network_interface { + network = "default" + } +} + +resource "google_iap_tunnel_instance_iam_binding" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance = "${google_compute_instance.test_vm.name}" + role = "roles/iap.tunnelResourceAccessor" + members = ["user:admin@hashicorptest.com"] +} +`, zone, instanceName) +} + +func testAccIapTunnelInstanceIamBinding_update(zone, instanceName string) string { + return fmt.Sprintf(` +resource "google_compute_instance" "test_vm" { + zone = "%s" + name = "%s" + machine_type = "n1-standard-1" + boot_disk { + initialize_params { + image = "debian-cloud/debian-9" + } + } + network_interface { + network = "default" + } +} + +resource "google_iap_tunnel_instance_iam_binding" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance = "${google_compute_instance.test_vm.name}" + role = "roles/iap.tunnelResourceAccessor" + members = [ + "user:admin@hashicorptest.com", + "user:paddy@hashicorp.com" + ] +} +`, zone, instanceName) +} + +func testAccIapTunnelInstanceIamMember_basic(zone, instanceName string) string { + return fmt.Sprintf(` +resource "google_compute_instance" "test_vm" { + zone = "%s" + name = "%s" + machine_type = "n1-standard-1" + boot_disk { + initialize_params { + image = "debian-cloud/debian-9" + } + } + network_interface { + network = "default" + } +} + +resource "google_iap_tunnel_instance_iam_member" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance = "${google_compute_instance.test_vm.name}" + role = "roles/iap.tunnelResourceAccessor" + member = "user:admin@hashicorptest.com" +} +`, zone, instanceName) +} + +func testAccIapTunnelInstanceIamPolicy_basic(zone, instanceName string) string { + return fmt.Sprintf(` +resource "google_compute_instance" "test_vm" { + zone = "%s" + name = "%s" + machine_type = "n1-standard-1" + boot_disk { + initialize_params { + image = "debian-cloud/debian-9" + } + } + network_interface { + network = "default" + } +} + +data "google_iam_policy" "foo" { + binding { + role = "roles/iap.tunnelResourceAccessor" + members = ["user:admin@hashicorptest.com"] + } +} + +resource "google_iap_tunnel_instance_iam_policy" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance = "${google_compute_instance.test_vm.name}" + policy_data = "${data.google_iam_policy.foo.policy_data}" +} +`, zone, instanceName) +} diff --git a/website/docs/r/google_iap_tunnel_instance_iam.markdown b/website/docs/r/google_iap_tunnel_instance_iam.markdown new file mode 100644 index 00000000000..c9a4903dcfc --- /dev/null +++ b/website/docs/r/google_iap_tunnel_instance_iam.markdown @@ -0,0 +1,126 @@ +--- +layout: "google" +page_title: "Google: google_iap_tunnel_instance_iam" +sidebar_current: "docs-google-iap-tunnel-instance-iam" +description: |- + Collection of resources to manage IAM policy for a IAP Tunnel Instance. +--- + +# IAM policy for IAP Tunnel Instance + +~> **Warning:** These resources are in beta, and should be used with the terraform-provider-google-beta provider. +See [Provider Versions](https://terraform.io/docs/providers/google/provider_versions.html) for more details on beta resources. + +Three different resources help you manage your IAM policy for IAP Tunnel Instance. Each of these resources serves a different use case: + +* `google_iap_tunnel_instance_iam_policy`: Authoritative. Sets the IAM policy for the instance and replaces any existing policy already attached. +* `google_iap_tunnel_instance_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 instance are preserved. +* `google_iap_tunnel_instance_iam_member`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the instance are preserved. + +~> **Note:** `google_iap_tunnel_instance_iam_policy` **cannot** be used in conjunction with `google_iap_tunnel_instance_iam_binding` and `google_iap_tunnel_instance_iam_member` or they will fight over what your policy should be. + +~> **Note:** `google_iap_tunnel_instance_iam_binding` resources **can be** used in conjunction with `google_iap_tunnel_instance_iam_member` resources **only if** they do not grant privilege to the same role. + +## google\_iap\_tunnel\_instance\_iam\_policy + +```hcl +data "google_iam_policy" "admin" { + binding { + role = "roles/editor" + + members = [ + "user:jane@example.com", + ] + } +} + +resource "google_iap_tunnel_instance_iam_policy" "instance" { + instance = "your-instance-name" + policy_data = "${data.google_iam_policy.admin.policy_data}" +} +``` + +## google\_iap\_tunnel\_instance\_iam\_binding + +```hcl +resource "google_iap_tunnel_instance_iam_binding" "instance" { + instance = "your-instance-name" + role = "roles/compute.networkUser" + + members = [ + "user:jane@example.com", + ] +} +``` + +## google\_iap\_tunnel\_instance\_iam\_member + +```hcl +resource "google_iap_tunnel_instance_iam_member" "instance" { + instance = "your-instance-name" + role = "roles/compute.networkUser" + member = "user:jane@example.com" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `instance` - (Required) The name of the instance. + +* `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_iap_tunnel_instance_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_iap_tunnel_instance_iam_policy`) The policy data generated by + a `google_iam_policy` data source. + +* `project` - (Optional) The ID of the project in which the resource belongs. If it + is not provided, the provider project is used. + +* `zone` - (Optional) The zone of the instance. If + unspecified, this defaults to the zone configured in the provider. + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are +exported: + +* `etag` - (Computed) The etag of the instance's IAM policy. + +## Import + +For all import syntaxes, the "resource in question" can take any of the following forms: + +* full self link or relative link (projects/{{project}}/zones/{{zone}}/instances/{{name}}) +* {{project}}/{{zone}}/{{name}} +* {{zone}}/{{name}} (project is taken from provider project) +* {{name}} (project and zone are taken from provider project) + +IAM member imports use space-delimited identifiers; the resource in question, the role, and the member identity, e.g. + +``` +$ terraform import google_iap_tunnel_instance_iam_member.instance "project-name/zone-name/instance-name roles/compute.networkUser user:foo@example.com" +``` + +IAM binding imports use space-delimited identifiers; the resource in question and the role, e.g. + +``` +$ terraform import google_iap_tunnel_instance_iam_binding.instance "project-name/zone-name/instance-name roles/compute.networkUser" +``` + +IAM policy imports use the identifier of the resource in question, e.g. + +``` +$ terraform import google_iap_tunnel_instance_iam_policy.instance project-name/zone-name/instance-name +``` diff --git a/website/google.erb b/website/google.erb index 4311f0cccfd..1590a33beeb 100644 --- a/website/google.erb +++ b/website/google.erb @@ -700,6 +700,22 @@ + +