Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add service account IAM support #840

Merged
merged 5 commits into from
Dec 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions google/iam_service_account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package google

import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/cloudresourcemanager/v1"
"google.golang.org/api/iam/v1"
)

var IamServiceAccountSchema = map[string]*schema.Schema{
"service_account_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateRegexp(ServiceAccountLinkRegex),
},
}

type ServiceAccountIamUpdater struct {
serviceAccountId string
Config *Config
}

func NewServiceAccountIamUpdater(d *schema.ResourceData, config *Config) (ResourceIamUpdater, error) {
return &ServiceAccountIamUpdater{
serviceAccountId: d.Get("service_account_id").(string),
Config: config,
}, nil
}

func ServiceAccountIdParseFunc(d *schema.ResourceData, _ *Config) error {
d.Set("service_account_id", d.Id())
return nil
}

func (u *ServiceAccountIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) {
p, err := u.Config.clientIAM.Projects.ServiceAccounts.GetIamPolicy(u.serviceAccountId).Do()

if err != nil {
return nil, fmt.Errorf("Error retrieving IAM policy for %s: %s", u.DescribeResource(), err)
}

cloudResourcePolicy, err := iamToResourceManagerPolicy(p)
if err != nil {
return nil, err
}

return cloudResourcePolicy, nil
}

func (u *ServiceAccountIamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error {
iamPolicy, err := resourceManagerToIamPolicy(policy)
if err != nil {
return err
}

_, err = u.Config.clientIAM.Projects.ServiceAccounts.SetIamPolicy(u.GetResourceId(), &iam.SetIamPolicyRequest{
Policy: iamPolicy,
}).Do()

if err != nil {
return fmt.Errorf("Error setting IAM policy for %s: %s", u.DescribeResource(), err)
}

return nil
}

func (u *ServiceAccountIamUpdater) GetResourceId() string {
return u.serviceAccountId
}

func (u *ServiceAccountIamUpdater) GetMutexKey() string {
return fmt.Sprintf("iam-service-account-%s", u.serviceAccountId)
}

func (u *ServiceAccountIamUpdater) DescribeResource() string {
return fmt.Sprintf("service account '%s'", u.serviceAccountId)
}

func resourceManagerToIamPolicy(p *cloudresourcemanager.Policy) (policy *iam.Policy, err error) {
policy = &iam.Policy{}

err = Convert(p, policy)

return
}

func iamToResourceManagerPolicy(p *iam.Policy) (policy *cloudresourcemanager.Policy, err error) {
policy = &cloudresourcemanager.Policy{}

err = Convert(p, policy)

return
}
3 changes: 3 additions & 0 deletions google/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,9 @@ func Provider() terraform.ResourceProvider {
"google_runtimeconfig_config": resourceRuntimeconfigConfig(),
"google_runtimeconfig_variable": resourceRuntimeconfigVariable(),
"google_service_account": resourceGoogleServiceAccount(),
"google_service_account_iam_binding": ResourceIamBindingWithImport(IamServiceAccountSchema, NewServiceAccountIamUpdater, ServiceAccountIdParseFunc),
"google_service_account_iam_member": ResourceIamMemberWithImport(IamServiceAccountSchema, NewServiceAccountIamUpdater, ServiceAccountIdParseFunc),
"google_service_account_iam_policy": ResourceIamPolicyWithImport(IamServiceAccountSchema, NewServiceAccountIamUpdater, ServiceAccountIdParseFunc),
"google_service_account_key": resourceGoogleServiceAccountKey(),
"google_storage_bucket": resourceStorageBucket(),
"google_storage_bucket_acl": resourceStorageBucketAcl(),
Expand Down
163 changes: 163 additions & 0 deletions google/resource_google_service_account_iam_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package google

import (
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"reflect"
"sort"
"testing"
)

func TestAccGoogleServiceAccountIamBinding(t *testing.T) {
t.Parallel()

account := acctest.RandomWithPrefix("tf-test")

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccGoogleServiceAccountIamBinding_basic(account),
Check: testAccCheckGoogleServiceAccountIam(account, "roles/viewer", []string{
fmt.Sprintf("serviceAccount:%s@%s.iam.gserviceaccount.com", account, getTestProjectFromEnv()),
}),
},
{
ResourceName: "google_service_account_iam_binding.foo",
ImportStateId: fmt.Sprintf("%s %s", getServiceAccountCanonicalId(account), "roles/viewer"),
ImportState: true,
},
},
})
}

func TestAccGoogleServiceAccountIamMember(t *testing.T) {
t.Parallel()

account := acctest.RandomWithPrefix("tf-test")
identity := fmt.Sprintf("serviceAccount:%s@%s.iam.gserviceaccount.com", account, getTestProjectFromEnv())

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccGoogleServiceAccountIamMember_basic(account),
Check: testAccCheckGoogleServiceAccountIam(account, "roles/editor", []string{identity}),
},
{
ResourceName: "google_service_account_iam_member.foo",
ImportStateId: fmt.Sprintf("%s %s %s", getServiceAccountCanonicalId(account), "roles/editor", identity),
ImportState: true,
},
},
})
}

func TestAccGoogleServiceAccountIamPolicy(t *testing.T) {
t.Parallel()

account := acctest.RandomWithPrefix("tf-test")

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccGoogleServiceAccountIamPolicy_basic(account),
Check: testAccCheckGoogleServiceAccountIam(account, "roles/owner", []string{
fmt.Sprintf("serviceAccount:%s@%s.iam.gserviceaccount.com", account, getTestProjectFromEnv()),
}),
},
{
ResourceName: "google_service_account_iam_policy.foo",
ImportStateId: getServiceAccountCanonicalId(account),
ImportState: true,
},
},
})
}

func testAccCheckGoogleServiceAccountIam(account, role string, members []string) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
p, err := config.clientIAM.Projects.ServiceAccounts.GetIamPolicy(getServiceAccountCanonicalId(account)).Do()
if err != nil {
return err
}

for _, binding := range p.Bindings {
if binding.Role == role {
sort.Strings(members)
sort.Strings(binding.Members)

if reflect.DeepEqual(members, binding.Members) {
return nil
}

return fmt.Errorf("Binding found but expected members is %v, got %v", members, binding.Members)
}
}

return fmt.Errorf("No binding for role %q", role)
}
}

func getServiceAccountCanonicalId(account string) string {
return fmt.Sprintf("projects/%s/serviceAccounts/%s@%s.iam.gserviceaccount.com", getTestProjectFromEnv(), account, getTestProjectFromEnv())
}

func testAccGoogleServiceAccountIamBinding_basic(account string) string {
return fmt.Sprintf(`
resource "google_service_account" "test_account" {
account_id = "%s"
display_name = "Iam Testing Account"
}

resource "google_service_account_iam_binding" "foo" {
service_account_id = "${google_service_account.test_account.id}"
role = "roles/viewer"
members = ["serviceAccount:${google_service_account.test_account.email}"]
}
`, account)
}

func testAccGoogleServiceAccountIamMember_basic(account string) string {
return fmt.Sprintf(`
resource "google_service_account" "test_account" {
account_id = "%s"
display_name = "Iam Testing Account"
}

resource "google_service_account_iam_member" "foo" {
service_account_id = "${google_service_account.test_account.id}"
role = "roles/editor"
member = "serviceAccount:${google_service_account.test_account.email}"
}
`, account)
}

func testAccGoogleServiceAccountIamPolicy_basic(account string) string {
return fmt.Sprintf(`
resource "google_service_account" "test_account" {
account_id = "%s"
display_name = "Iam Testing Account"
}

data "google_iam_policy" "foo" {
binding {
role = "roles/owner"

members = ["serviceAccount:${google_service_account.test_account.email}"]
}
}

resource "google_service_account_iam_policy" "foo" {
service_account_id = "${google_service_account.test_account.id}"
policy_data = "${data.google_iam_policy.foo.policy_data}"
}
`, account)
}
103 changes: 103 additions & 0 deletions website/docs/r/google_service_account_iam.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
---
layout: "google"
page_title: "Google: google_service_account_iam"
sidebar_current: "docs-google-service-account-iam"
description: |-
Collection of resources to manage IAM policy for a service account.
---

# IAM policy for service account

When managing IAM roles, you can treat a service account either as a resource or as an identity. This resource is to add iam policy bindings to a service account resource.

Three different resources help you manage your IAM policy for a service account. Each of these resources serves a different use case:

* `google_service_account_iam_policy`: Authoritative. Sets the IAM policy for the service account and replaces any existing policy already attached.
* `google_service_account_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 service account are preserved.
* `google_service_account_iam_member`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the service account are preserved.

~> **Note:** `google_service_account_iam_policy` **cannot** be used in conjunction with `google_service_account_iam_binding` and `google_service_account_iam_member` or they will fight over what your policy should be.

~> **Note:** `google_service_account_iam_binding` resources **can be** used in conjunction with `google_service_account_iam_member` resources **only if** they do not grant privilege to the same role.

## google\_service\_account\_iam\_policy

```hcl
data "google_iam_policy" "admin" {
binding {
role = "roles/editor"

members = [
"user:jane@example.com",
]
}
}

resource "google_service_account_iam_policy" "admin-account-iam" {
service_account_id = "your-service-account-id"
policy_data = "${data.google_iam_policy.admin.policy_data}"
}
```

## google\_service\_account\_iam\_binding

```hcl
resource "google_service_account_iam_binding" "admin-account-iam" {
service_account_id = "your-service-account-id"
role = "roles/editor"

members = [
"user:jane@example.com",
]
}
```

## google\_service\_account\_iam\_member

```hcl
resource "google_service_account_iam_member" "admin-account-iam" {
service_account_id = "your-service-account-id"
role = "roles/editor"
member = "user:jane@example.com"
}
```

## Argument Reference

The following arguments are supported:

* `service_account_id` - (Required) The service account id to apply policy to.

* `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 Google Apps domain 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_service_account_iam_binding` can be used per role.

* `policy_data` - (Required only by `google_service_account_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 service account IAM policy.

## Import

Service account IAM resources can be imported using the project, service account email, role and member.

```
$ terraform import google_service_account_iam_policy.admin-account-iam projects/{your-project-id}/serviceAccounts/{your-service-account-email}

$ terraform import google_service_account_iam_binding.admin-account-iam "projects/{your-project-id}/serviceAccounts/{your-service-account-email} roles/editor"

$ terraform import google_service_account_iam_member.admin-account-iam "projects/{your-project-id}/serviceAccounts/{your-service-account-email} roles/editor foo@example.com"
```
9 changes: 9 additions & 0 deletions website/google.erb
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,15 @@
</li>
<li<%= sidebar_current("docs-google-service-account") %>>
<a href="/docs/providers/google/r/google_service_account.html">google_service_account</a>
</li>
<li<%= sidebar_current("docs-google-service-account-iam") %>>
<a href="/docs/providers/google/r/google_service_account_iam.html">google_service_account_iam_binding</a>
</li>
<li<%= sidebar_current("docs-google-service-account-iam") %>>
<a href="/docs/providers/google/r/google_service_account_iam.html">google_service_account_iam_member</a>
</li>
<li<%= sidebar_current("docs-google-service-account-iam") %>>
<a href="/docs/providers/google/r/google_service_account_iam.html">google_service_account_iam_policy</a>
</li>
<li<%= sidebar_current("docs-google-service-account-key") %>>
<a href="/docs/providers/google/r/google_service_account_key.html">google_service_account_key</a>
Expand Down