diff --git a/google/field_helpers.go b/google/field_helpers.go index 06ea3ff1..a822c4ea 100644 --- a/google/field_helpers.go +++ b/google/field_helpers.go @@ -62,6 +62,10 @@ func ParseMachineTypesFieldValue(machineType string, d TerraformResourceData, co return parseZonalFieldValue("machineTypes", machineType, "project", "zone", d, config, false) } +func ParseInstanceFieldValue(instance string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) { + return parseZonalFieldValue("instances", instance, "project", "zone", d, config, false) +} + func ParseInstanceGroupFieldValue(instanceGroup string, d TerraformResourceData, config *Config) (*ZonalFieldValue, error) { return parseZonalFieldValue("instanceGroups", instanceGroup, "project", "zone", d, config, false) } diff --git a/google/iam_compute_instance.go b/google/iam_compute_instance.go new file mode 100644 index 00000000..c6dafce8 --- /dev/null +++ b/google/iam_compute_instance.go @@ -0,0 +1,147 @@ +package google + +import ( + "fmt" + "strings" + + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/schema" + "google.golang.org/api/cloudresourcemanager/v1" + "google.golang.org/api/compute/v1" +) + +var IamComputeInstanceSchema = map[string]*schema.Schema{ + "instance_name": { + 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 ComputeInstanceIamUpdater struct { + project string + zone string + resourceId string + Config *Config +} + +func NewComputeInstanceIamUpdater(d *schema.ResourceData, config *Config) (ResourceIamUpdater, error) { + project, err := getProject(d, config) + if err != nil { + return nil, err + } + + zone, err := getZone(d, config) + if err != nil { + return nil, err + } + + return &ComputeInstanceIamUpdater{ + project: project, + zone: zone, + resourceId: d.Get("instance_name").(string), + Config: config, + }, nil +} + +func ComputeInstanceIdParseFunc(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_name", fv.Name) + + // Explicitly set the id so imported resources have the same ID format as non-imported ones. + d.SetId(fv.RelativeLink()) + return nil +} + +func (u *ComputeInstanceIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { + p, err := u.Config.clientCompute.Instances.GetIamPolicy(u.project, u.zone, u.resourceId).Do() + + if err != nil { + return nil, errwrap.Wrapf(fmt.Sprintf("Error retrieving IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + cloudResourcePolicy, err := computeToResourceManagerPolicy(p) + + if err != nil { + return nil, errwrap.Wrapf(fmt.Sprintf("Invalid IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + return cloudResourcePolicy, nil +} + +func (u *ComputeInstanceIamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error { + computePolicy, err := resourceManagerToComputePolicy(policy) + + if err != nil { + return errwrap.Wrapf(fmt.Sprintf("Invalid IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + req := &compute.ZoneSetPolicyRequest{ + Policy: computePolicy, + } + _, err = u.Config.clientCompute.Instances.SetIamPolicy(u.project, u.zone, u.resourceId, req).Do() + + if err != nil { + return errwrap.Wrapf(fmt.Sprintf("Error setting IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + return nil +} + +func (u *ComputeInstanceIamUpdater) GetResourceId() string { + return fmt.Sprintf("projects/%s/zones/%s/instances/%s", u.project, u.zone, u.resourceId) +} + +func (u *ComputeInstanceIamUpdater) GetMutexKey() string { + return fmt.Sprintf("iam-compute-Instance-%s-%s-%s", u.project, u.zone, u.resourceId) +} + +func (u *ComputeInstanceIamUpdater) DescribeResource() string { + return fmt.Sprintf("Compute Instance %s/%s/%s", u.project, u.zone, u.resourceId) +} diff --git a/google/provider.go b/google/provider.go index 1635cf23..029ea8df 100644 --- a/google/provider.go +++ b/google/provider.go @@ -173,6 +173,9 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_compute_instance_from_template": resourceComputeInstanceFromTemplate(), "google_compute_instance_group": resourceComputeInstanceGroup(), "google_compute_instance_group_manager": resourceComputeInstanceGroupManager(), + "google_compute_instance_iam_binding": ResourceIamBindingWithImport(IamComputeInstanceSchema, NewComputeInstanceIamUpdater, ComputeInstanceIdParseFunc), + "google_compute_instance_iam_member": ResourceIamMemberWithImport(IamComputeInstanceSchema, NewComputeInstanceIamUpdater, ComputeInstanceIdParseFunc), + "google_compute_instance_iam_policy": ResourceIamPolicyWithImport(IamComputeInstanceSchema, NewComputeInstanceIamUpdater, ComputeInstanceIdParseFunc), "google_compute_instance_template": resourceComputeInstanceTemplate(), "google_compute_network_peering": resourceComputeNetworkPeering(), "google_compute_project_metadata": resourceComputeProjectMetadata(), diff --git a/google/resource_compute_instance_iam_test.go b/google/resource_compute_instance_iam_test.go new file mode 100644 index 00000000..aeb4724a --- /dev/null +++ b/google/resource_compute_instance_iam_test.go @@ -0,0 +1,230 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccComputeInstanceIamBinding(t *testing.T) { + t.Parallel() + + project := getTestProjectFromEnv() + role := "roles/compute.osLogin" + 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: testAccComputeInstanceIamBinding_basic(zone, instanceName, role), + }, + { + ResourceName: "google_compute_instance_iam_binding.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s %s", project, zone, instanceName, role), + ImportState: true, + ImportStateVerify: true, + }, + { + // Test Iam Binding update + Config: testAccComputeInstanceIamBinding_update(zone, instanceName, role), + }, + { + ResourceName: "google_compute_instance_iam_binding.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s %s", project, zone, instanceName, role), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeInstanceIamMember(t *testing.T) { + t.Parallel() + + project := getTestProjectFromEnv() + role := "roles/compute.osLogin" + 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: testAccComputeInstanceIamMember_basic(zone, instanceName, role), + }, + { + ResourceName: "google_compute_instance_iam_member.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s %s user:admin@hashicorptest.com", project, zone, instanceName, role), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeInstanceIamPolicy(t *testing.T) { + t.Parallel() + + project := getTestProjectFromEnv() + role := "roles/compute.osLogin" + 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: testAccComputeInstanceIamPolicy_basic(zone, instanceName, role), + }, + // Test a few import formats + { + ResourceName: "google_compute_instance_iam_policy.foo", + ImportStateId: fmt.Sprintf("projects/%s/zones/%s/instances/%s", project, zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + { + ResourceName: "google_compute_instance_iam_policy.foo", + ImportStateId: fmt.Sprintf("%s/%s/%s", project, zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + { + ResourceName: "google_compute_instance_iam_policy.foo", + ImportStateId: fmt.Sprintf("%s/%s", zone, instanceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccComputeInstanceIamMember_basic(zone, instanceName, roleId 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_compute_instance_iam_member" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance_name = "${google_compute_instance.test_vm.name}" + role = "%s" + member = "user:admin@hashicorptest.com" + } + +`, zone, instanceName, roleId) +} + +func testAccComputeInstanceIamPolicy_basic(zone, instanceName, roleId 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 = "%s" + members = ["user:admin@hashicorptest.com"] + } + } + + resource "google_compute_instance_iam_policy" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance_name = "${google_compute_instance.test_vm.name}" + policy_data = "${data.google_iam_policy.foo.policy_data}" + } + +`, zone, instanceName, roleId) +} + +func testAccComputeInstanceIamBinding_basic(zone, instanceName, roleId 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_compute_instance_iam_binding" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance_name = "${google_compute_instance.test_vm.name}" + role = "%s" + members = ["user:admin@hashicorptest.com"] + } + +`, zone, instanceName, roleId) +} + +func testAccComputeInstanceIamBinding_update(zone, instanceName, roleId 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_compute_instance_iam_binding" "foo" { + project = "${google_compute_instance.test_vm.project}" + zone = "${google_compute_instance.test_vm.zone}" + instance_name = "${google_compute_instance.test_vm.name}" + role = "%s" + members = ["user:admin@hashicorptest.com", "user:paddy@hashicorp.com"] + } + +`, zone, instanceName, roleId) +} diff --git a/website/docs/r/compute_instance_iam.html.markdown b/website/docs/r/compute_instance_iam.html.markdown new file mode 100644 index 00000000..9c54414e --- /dev/null +++ b/website/docs/r/compute_instance_iam.html.markdown @@ -0,0 +1,123 @@ +--- +layout: "google" +page_title: "Google: google_compute_instance_iam" +sidebar_current: "docs-google-compute-instance-iam" +description: |- + Collection of resources to manage IAM policy for a GCE instance. +--- + +# IAM policy for GCE instance + +Three different resources help you manage your IAM policy for GCE instance. Each of these resources serves a different use case: + +* `google_compute_instance_iam_policy`: Authoritative. Sets the IAM policy for the instance and replaces any existing policy already attached. +* `google_compute_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_compute_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_compute_instance_iam_policy` **cannot** be used in conjunction with `google_compute_instance_iam_binding` and `google_compute_instance_iam_member` or they will fight over what your policy should be. + +~> **Note:** `google_compute_instance_iam_binding` resources **can be** used in conjunction with `google_compute_instance_iam_member` resources **only if** they do not grant privilege to the same role. + +## google\_compute\_instance\_iam\_policy + +```hcl +data "google_iam_policy" "admin" { + binding { + role = "roles/compute.osLogin" + + members = [ + "user:jane@example.com", + ] + } +} + +resource "google_compute_instance_iam_policy" "instance" { + instance_name = "your-instance-name" + policy_data = "${data.google_iam_policy.admin.policy_data}" +} +``` + +## google\_compute\_instance\_iam\_binding + +```hcl +resource "google_compute_instance_iam_binding" "instance" { + instance_name = "your-instance-name" + role = "roles/compute.osLogin" + + members = [ + "user:jane@example.com", + ] +} +``` + +## google\compute\_instance\_iam\_member + +```hcl +resource "google_compute_instance_iam_member" "instance" { + instance_name = "your-instance-name" + role = "roles/compute.osLogin" + member = "user:jane@example.com" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `instance_name` - (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_compute_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_compute_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_compute_instance_iam_member.instance "project-name/zone-name/instance-name roles/compute.osLogin user:foo@example.com" +``` + +IAM binding imports use space-delimited identifiers; the resource in question and the role, e.g. + +``` +$ terraform import google_compute_instance_iam_binding.instance "project-name/zone-name/instance-name roles/compute.osLogin" +``` + +IAM policy imports use the identifier of the resource in question, e.g. + +``` +$ terraform import google_compute_instance_iam_policy.instance project-name/zone-name/instance-name +``` diff --git a/website/google.erb b/website/google.erb index 5a0da30a..ebcb3616 100644 --- a/website/google.erb +++ b/website/google.erb @@ -391,6 +391,18 @@ google_compute_instance + > + google_compute_instance_iam_binding + + + > + google_compute_instance_iam_member + + + > + google_compute_instance_iam_policy + + > google_compute_instance_from_template