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 google_impersonated_credential datasource #3211

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
98 changes: 98 additions & 0 deletions google/data_source_google_impersonated_credential.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package google

import (
"context"
"fmt"
"log"
"net/http"

"strings"
"time"

"github.com/hashicorp/terraform/helper/schema"
"golang.org/x/oauth2"
iamcredentials "google.golang.org/api/iamcredentials/v1"
)

func dataSourceGoogleImpersonatedCredential() *schema.Resource {

return &schema.Resource{
Read: dataSourceImpersonatedCredentialRead,
Schema: map[string]*schema.Schema{
"source_access_token": {
Type: schema.TypeString,
Optional: true,
},
"target_service_account": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateRegexp("(" + strings.Join(PossibleServiceAccountNames, "|") + ")"),
},
"access_token": {
Type: schema.TypeString,
Sensitive: true,
Computed: true,
},
"scopes": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
StateFunc: func(v interface{}) string {
return canonicalizeServiceScope(v.(string))
},
},
// ValidateFunc is not yet supported on lists or sets.
},
"delegates": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateRegexp(ServiceAccountLinkRegex),
},
},
"lifetime": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateDuration(), // duration <=3600s; TODO: support validteDuration(min,max)
Default: "3600s",
},
},
}
}

func dataSourceImpersonatedCredentialRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
log.Printf("[INFO] Acquire Impersonated credentials for %s", d.Get("target_service_account").(string))

d.SetId(time.Now().UTC().String())
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved
var client *http.Client
if d.Get("source_access_token") != "" {
rootTokenSource := oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: d.Get("source_access_token").(string),
})
client = oauth2.NewClient(context.TODO(), rootTokenSource)
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved
} else {
client = config.client
}

service, err := iamcredentials.New(client)
if err != nil {
return err
}
name := fmt.Sprintf("projects/-/serviceAccounts/%s", d.Get("target_service_account").(string))
tokenRequest := &iamcredentials.GenerateAccessTokenRequest{
Lifetime: d.Get("lifetime").(string),
Delegates: convertStringSet(d.Get("delegates").(*schema.Set)),
Scope: canonicalizeServiceScopes(convertStringSet(d.Get("scopes").(*schema.Set))),
}
at, err := service.Projects.ServiceAccounts.GenerateAccessToken(name, tokenRequest).Do()
if err != nil {
return err
}

d.Set("access_token", at.AccessToken)

return nil
}
64 changes: 64 additions & 0 deletions google/data_source_google_impersonated_credential_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package google

import (
"testing"

"fmt"

"github.com/hashicorp/terraform/helper/resource"
)

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

resourceName := "data.google_impersonated_credential.default"

targetServiceAccount := getTestServiceAccountFromEnv(t)
scopes := []string{"storage-ro", "https://www.googleapis.com/auth/cloud-platform"}
delegates := []string{}
lifetime := "30s"
targetProject := getTestProjectFromEnv()

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckGoogleImpersonatedCredential_datasource(targetServiceAccount, scopes, delegates, lifetime, targetProject),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "target_service_account", targetServiceAccount),
resource.TestCheckResourceAttr(resourceName, "lifetime", lifetime),
),
},
},
})
}

func testAccCheckGoogleImpersonatedCredential_datasource(targetServiceAccount string, scopes []string, delegates []string, lifetime string, target_project string) string {
return fmt.Sprintf(`

provider "google" {}

data "google_client_config" "default" {
provider = "google"
}

data "google_impersonated_credential" "default" {
provider = "google"
target_service_account = "%s"
scopes = ["storage-ro", "https://www.googleapis.com/auth/cloud-platform"]
lifetime = "%s"
}

provider "google" {
alias = "impersonated"
access_token = "${data.google_impersonated_credential.default.access_token}"
}

data "google_project" "project" {
provider = "google.impersonated"
project_id = "%s"
}

`, targetServiceAccount, lifetime, target_project)
}
1 change: 1 addition & 0 deletions google/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ func Provider() terraform.ResourceProvider {
"google_container_registry_image": dataSourceGoogleContainerImage(),
"google_iam_policy": dataSourceGoogleIamPolicy(),
"google_iam_role": dataSourceGoogleIamRole(),
"google_impersonated_credential": dataSourceGoogleImpersonatedCredential(),
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved
"google_kms_secret": dataSourceGoogleKmsSecret(),
"google_kms_key_ring": dataSourceGoogleKmsKeyRing(),
"google_kms_crypto_key": dataSourceGoogleKmsCryptoKey(),
Expand Down
2 changes: 1 addition & 1 deletion google/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

const (
// Copied from the official Google Cloud auto-generated client.
ProjectRegex = "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))"
ProjectRegex = "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)|-)"
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved
RegionRegex = "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?"
SubnetworkRegex = "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?"

Expand Down
84 changes: 84 additions & 0 deletions website/docs/d/google_impersonated_credential.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
layout: "google"
page_title: "Google: google_impersonated_credential"
sidebar_current: "docs-google-impersonated-credential"
description: |-
Produces access_token for impersonated service accounts
---

# google\_impersonated\_credential

This data source provides a google `oauth2` `access_token` for a different service account than the one initially running the script. You can
then use this new token to access resources the original caller would not have permissions on otherwise.
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved

For more information see
[the official documentation](https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials) as well as [iamcredentials.generateAccessToken()](https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/generateAccessToken)

## Example Usage

To allow `service_A` to impersonate `service_B`, grant the [Service Account Token Creator](https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role) on B to A.

In the IAM policy below, `service_A` is given the Token Creator role impersonate `service_B`

```hcl
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved
$ cat service_policy.json
{
"bindings": [
{
"members": [
"[email protected] "
],
"role": "roles/iam.serviceAccountTokenCreator",
}
]
}

$ gcloud iam service-accounts set-iam-policy [email protected] service_policy.json
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved
```

Once the IAM permissions are set, you can apply the new token to a provider bootstrapped with it. Any resources that references the new provider will run as the new identity.
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved

In the example below, `google_project` will run as `service_B`.

```hcl
provider "google" {}

data "google_client_config" "default" {
provider = "google"
}

data "google_impersonated_credential" "default" {
provider = "google"
target_service_account = "[email protected]"
scopes = ["devstorage.read_only", "cloud-platform"]
lifetime = "300s"
}

provider "google" {
alias = "impersonated"
access_token = "${data.google_impersonated_credential.default.access_token}"
}

data "google_project" "project" {
provider = "google.impersonated"
project_id = "target-project"
}
```

> *Note*: the generated token is non-refreshable and can have a maximum `lifetime` of `3600` seconds.
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved

## Argument Reference

The following arguments are supported:

* `target_service_account` (Required) - The service account _to_ impersonate (e.g. `[email protected]`)
* `scopes` (Required) - The scopes the new credential should have (e.g. `["devstorage.read_only", "cloud-platform"]`)
* `delegates` (Optional) - Deegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name. (e.g. `["projects/-/serviceAccounts/[email protected]"]`)
* `lifetime` (Optional) Lifetime of the impersonated token (defaults to its max: `3600s`).
* `source_access_token` (Optional) - The source token to bootstrap this module.
salrashid123 marked this conversation as resolved.
Show resolved Hide resolved

## Attributes Reference

The following attribute is exported:

* `access_token` - The `access_token` representing the new generated identity.