gcp.serviceaccount.getAccountAccessToken
This data source provides a google oauth2 access_token for a different service account than the one initially running the script.
For more information see the official documentation as well as iamcredentials.generateAccessToken()
Example Usage
To allow service_A to impersonate service_B, grant the Service Account Token Creator on B to A.
In the IAM policy below, service_A is given the Token Creator role impersonate service_B
import * as pulumi from "@pulumi/pulumi";
import * as gcp from "@pulumi/gcp";
const token_creator_iam = new gcp.serviceaccount.IAMBinding("token-creator-iam", {
    serviceAccountId: "projects/-/serviceAccounts/service_B@projectB.iam.gserviceaccount.com",
    role: "roles/iam.serviceAccountTokenCreator",
    members: ["serviceAccount:service_A@projectA.iam.gserviceaccount.com"],
});
import pulumi
import pulumi_gcp as gcp
token_creator_iam = gcp.serviceaccount.IAMBinding("token-creator-iam",
    service_account_id="projects/-/serviceAccounts/service_B@projectB.iam.gserviceaccount.com",
    role="roles/iam.serviceAccountTokenCreator",
    members=["serviceAccount:service_A@projectA.iam.gserviceaccount.com"])
package main
import (
	"github.com/pulumi/pulumi-gcp/sdk/v9/go/gcp/serviceaccount"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		_, err := serviceaccount.NewIAMBinding(ctx, "token-creator-iam", &serviceaccount.IAMBindingArgs{
			ServiceAccountId: pulumi.String("projects/-/serviceAccounts/service_B@projectB.iam.gserviceaccount.com"),
			Role:             pulumi.String("roles/iam.serviceAccountTokenCreator"),
			Members: pulumi.StringArray{
				pulumi.String("serviceAccount:service_A@projectA.iam.gserviceaccount.com"),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})
}
using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Gcp = Pulumi.Gcp;
return await Deployment.RunAsync(() => 
{
    var token_creator_iam = new Gcp.ServiceAccount.IAMBinding("token-creator-iam", new()
    {
        ServiceAccountId = "projects/-/serviceAccounts/service_B@projectB.iam.gserviceaccount.com",
        Role = "roles/iam.serviceAccountTokenCreator",
        Members = new[]
        {
            "serviceAccount:service_A@projectA.iam.gserviceaccount.com",
        },
    });
});
package generated_program;
import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.gcp.serviceaccount.IAMBinding;
import com.pulumi.gcp.serviceaccount.IAMBindingArgs;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }
    public static void stack(Context ctx) {
        var token_creator_iam = new IAMBinding("token-creator-iam", IAMBindingArgs.builder()
            .serviceAccountId("projects/-/serviceAccounts/service_B@projectB.iam.gserviceaccount.com")
            .role("roles/iam.serviceAccountTokenCreator")
            .members("serviceAccount:service_A@projectA.iam.gserviceaccount.com")
            .build());
    }
}
resources:
  token-creator-iam:
    type: gcp:serviceaccount:IAMBinding
    properties:
      serviceAccountId: projects/-/serviceAccounts/service_B@projectB.iam.gserviceaccount.com
      role: roles/iam.serviceAccountTokenCreator
      members:
        - serviceAccount:service_A@projectA.iam.gserviceaccount.com
Once the IAM permissions are set, you can apply the new token to a provider bootstrapped with it. Any resources that references the aliased provider will run as the new identity.
In the example below, gcp.organizations.Project will run as service_B.
import * as pulumi from "@pulumi/pulumi";
import * as gcp from "@pulumi/gcp";
export = async () => {
    const _default = await gcp.organizations.getClientConfig({});
    const defaultGetAccountAccessToken = await gcp.serviceaccount.getAccountAccessToken({
        targetServiceAccount: "service_B@projectB.iam.gserviceaccount.com",
        scopes: [
            "userinfo-email",
            "cloud-platform",
        ],
        lifetime: "300s",
    });
    const me = await gcp.organizations.getClientOpenIdUserInfo({});
    return {
        "target-email": me.email,
    };
}
import pulumi
import pulumi_gcp as gcp
default = gcp.organizations.get_client_config()
default_get_account_access_token = gcp.serviceaccount.get_account_access_token(target_service_account="service_B@projectB.iam.gserviceaccount.com",
    scopes=[
        "userinfo-email",
        "cloud-platform",
    ],
    lifetime="300s")
me = gcp.organizations.get_client_open_id_user_info()
pulumi.export("target-email", me.email)
package main
import (
	"github.com/pulumi/pulumi-gcp/sdk/v9/go/gcp/organizations"
	"github.com/pulumi/pulumi-gcp/sdk/v9/go/gcp/serviceaccount"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		_, err := organizations.GetClientConfig(ctx, map[string]interface{}{}, nil)
		if err != nil {
			return err
		}
		_, err = serviceaccount.GetAccountAccessToken(ctx, &serviceaccount.GetAccountAccessTokenArgs{
			TargetServiceAccount: "service_B@projectB.iam.gserviceaccount.com",
			Scopes: []string{
				"userinfo-email",
				"cloud-platform",
			},
			Lifetime: pulumi.StringRef("300s"),
		}, nil)
		if err != nil {
			return err
		}
		me, err := organizations.GetClientOpenIdUserInfo(ctx, map[string]interface{}{}, nil)
		if err != nil {
			return err
		}
		ctx.Export("target-email", me.Email)
		return nil
	})
}
using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Gcp = Pulumi.Gcp;
return await Deployment.RunAsync(() => 
{
    var @default = Gcp.Organizations.GetClientConfig.Invoke();
    var defaultGetAccountAccessToken = Gcp.ServiceAccount.GetAccountAccessToken.Invoke(new()
    {
        TargetServiceAccount = "service_B@projectB.iam.gserviceaccount.com",
        Scopes = new[]
        {
            "userinfo-email",
            "cloud-platform",
        },
        Lifetime = "300s",
    });
    var me = Gcp.Organizations.GetClientOpenIdUserInfo.Invoke();
    return new Dictionary<string, object?>
    {
        ["target-email"] = me.Apply(getClientOpenIdUserInfoResult => getClientOpenIdUserInfoResult.Email),
    };
});
package generated_program;
import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.gcp.organizations.OrganizationsFunctions;
import com.pulumi.gcp.serviceaccount.ServiceaccountFunctions;
import com.pulumi.gcp.serviceaccount.inputs.GetAccountAccessTokenArgs;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }
    public static void stack(Context ctx) {
        final var default = OrganizationsFunctions.getClientConfig(%!v(PANIC=Format method: runtime error: invalid memory address or nil pointer dereference);
        final var defaultGetAccountAccessToken = ServiceaccountFunctions.getAccountAccessToken(GetAccountAccessTokenArgs.builder()
            .targetServiceAccount("service_B@projectB.iam.gserviceaccount.com")
            .scopes(            
                "userinfo-email",
                "cloud-platform")
            .lifetime("300s")
            .build());
        final var me = OrganizationsFunctions.getClientOpenIdUserInfo(%!v(PANIC=Format method: runtime error: invalid memory address or nil pointer dereference);
        ctx.export("target-email", me.email());
    }
}
variables:
  default:
    fn::invoke:
      function: gcp:organizations:getClientConfig
      arguments: {}
  defaultGetAccountAccessToken:
    fn::invoke:
      function: gcp:serviceaccount:getAccountAccessToken
      arguments:
        targetServiceAccount: service_B@projectB.iam.gserviceaccount.com
        scopes:
          - userinfo-email
          - cloud-platform
        lifetime: 300s
  me:
    fn::invoke:
      function: gcp:organizations:getClientOpenIdUserInfo
      arguments: {}
outputs:
  target-email: ${me.email}
Note: the generated token is non-refreshable and can have a maximum
lifetimeof3600seconds.
Using getAccountAccessToken
Two invocation forms are available. The direct form accepts plain arguments and either blocks until the result value is available, or returns a Promise-wrapped result. The output form accepts Input-wrapped arguments and returns an Output-wrapped result.
function getAccountAccessToken(args: GetAccountAccessTokenArgs, opts?: InvokeOptions): Promise<GetAccountAccessTokenResult>
function getAccountAccessTokenOutput(args: GetAccountAccessTokenOutputArgs, opts?: InvokeOptions): Output<GetAccountAccessTokenResult>def get_account_access_token(delegates: Optional[Sequence[str]] = None,
                             lifetime: Optional[str] = None,
                             scopes: Optional[Sequence[str]] = None,
                             target_service_account: Optional[str] = None,
                             opts: Optional[InvokeOptions] = None) -> GetAccountAccessTokenResult
def get_account_access_token_output(delegates: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
                             lifetime: Optional[pulumi.Input[str]] = None,
                             scopes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
                             target_service_account: Optional[pulumi.Input[str]] = None,
                             opts: Optional[InvokeOptions] = None) -> Output[GetAccountAccessTokenResult]func GetAccountAccessToken(ctx *Context, args *GetAccountAccessTokenArgs, opts ...InvokeOption) (*GetAccountAccessTokenResult, error)
func GetAccountAccessTokenOutput(ctx *Context, args *GetAccountAccessTokenOutputArgs, opts ...InvokeOption) GetAccountAccessTokenResultOutput> Note: This function is named GetAccountAccessToken in the Go SDK.
public static class GetAccountAccessToken 
{
    public static Task<GetAccountAccessTokenResult> InvokeAsync(GetAccountAccessTokenArgs args, InvokeOptions? opts = null)
    public static Output<GetAccountAccessTokenResult> Invoke(GetAccountAccessTokenInvokeArgs args, InvokeOptions? opts = null)
}public static CompletableFuture<GetAccountAccessTokenResult> getAccountAccessToken(GetAccountAccessTokenArgs args, InvokeOptions options)
public static Output<GetAccountAccessTokenResult> getAccountAccessToken(GetAccountAccessTokenArgs args, InvokeOptions options)
fn::invoke:
  function: gcp:serviceaccount/getAccountAccessToken:getAccountAccessToken
  arguments:
    # arguments dictionaryThe following arguments are supported:
- Scopes List<string>
- The scopes the new credential should have (e.g. ["cloud-platform"])
- TargetService stringAccount 
- The service account to impersonate (e.g. service_B@your-project-id.iam.gserviceaccount.com)
- Delegates List<string>
- Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name. (e.g. ["projects/-/serviceAccounts/delegate-svc-account@project-id.iam.gserviceaccount.com"])
- Lifetime string
- Lifetime of the impersonated token (defaults to its max: 3600s).
- Scopes []string
- The scopes the new credential should have (e.g. ["cloud-platform"])
- TargetService stringAccount 
- The service account to impersonate (e.g. service_B@your-project-id.iam.gserviceaccount.com)
- Delegates []string
- Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name. (e.g. ["projects/-/serviceAccounts/delegate-svc-account@project-id.iam.gserviceaccount.com"])
- Lifetime string
- Lifetime of the impersonated token (defaults to its max: 3600s).
- scopes List<String>
- The scopes the new credential should have (e.g. ["cloud-platform"])
- targetService StringAccount 
- The service account to impersonate (e.g. service_B@your-project-id.iam.gserviceaccount.com)
- delegates List<String>
- Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name. (e.g. ["projects/-/serviceAccounts/delegate-svc-account@project-id.iam.gserviceaccount.com"])
- lifetime String
- Lifetime of the impersonated token (defaults to its max: 3600s).
- scopes string[]
- The scopes the new credential should have (e.g. ["cloud-platform"])
- targetService stringAccount 
- The service account to impersonate (e.g. service_B@your-project-id.iam.gserviceaccount.com)
- delegates string[]
- Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name. (e.g. ["projects/-/serviceAccounts/delegate-svc-account@project-id.iam.gserviceaccount.com"])
- lifetime string
- Lifetime of the impersonated token (defaults to its max: 3600s).
- scopes Sequence[str]
- The scopes the new credential should have (e.g. ["cloud-platform"])
- target_service_ straccount 
- The service account to impersonate (e.g. service_B@your-project-id.iam.gserviceaccount.com)
- delegates Sequence[str]
- Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name. (e.g. ["projects/-/serviceAccounts/delegate-svc-account@project-id.iam.gserviceaccount.com"])
- lifetime str
- Lifetime of the impersonated token (defaults to its max: 3600s).
- scopes List<String>
- The scopes the new credential should have (e.g. ["cloud-platform"])
- targetService StringAccount 
- The service account to impersonate (e.g. service_B@your-project-id.iam.gserviceaccount.com)
- delegates List<String>
- Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name. (e.g. ["projects/-/serviceAccounts/delegate-svc-account@project-id.iam.gserviceaccount.com"])
- lifetime String
- Lifetime of the impersonated token (defaults to its max: 3600s).
getAccountAccessToken Result
The following output properties are available:
- AccessToken string
- The access_tokenrepresenting the new generated identity.
- Id string
- The provider-assigned unique ID for this managed resource.
- Scopes List<string>
- TargetService stringAccount 
- Delegates List<string>
- Lifetime string
- AccessToken string
- The access_tokenrepresenting the new generated identity.
- Id string
- The provider-assigned unique ID for this managed resource.
- Scopes []string
- TargetService stringAccount 
- Delegates []string
- Lifetime string
- accessToken String
- The access_tokenrepresenting the new generated identity.
- id String
- The provider-assigned unique ID for this managed resource.
- scopes List<String>
- targetService StringAccount 
- delegates List<String>
- lifetime String
- accessToken string
- The access_tokenrepresenting the new generated identity.
- id string
- The provider-assigned unique ID for this managed resource.
- scopes string[]
- targetService stringAccount 
- delegates string[]
- lifetime string
- access_token str
- The access_tokenrepresenting the new generated identity.
- id str
- The provider-assigned unique ID for this managed resource.
- scopes Sequence[str]
- target_service_ straccount 
- delegates Sequence[str]
- lifetime str
- accessToken String
- The access_tokenrepresenting the new generated identity.
- id String
- The provider-assigned unique ID for this managed resource.
- scopes List<String>
- targetService StringAccount 
- delegates List<String>
- lifetime String
Package Details
- Repository
- Google Cloud (GCP) Classic pulumi/pulumi-gcp
- License
- Apache-2.0
- Notes
- This Pulumi package is based on the google-betaTerraform Provider.
