1. Packages
  2. Google Cloud (GCP) Classic
  3. API Docs
  4. serviceaccount
  5. getAccountAccessToken
Google Cloud Classic v7.28.0 published on Friday, Jun 21, 2024 by Pulumi

gcp.serviceaccount.getAccountAccessToken

Explore with Pulumi AI

gcp logo
Google Cloud Classic v7.28.0 published on Friday, Jun 21, 2024 by Pulumi

    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/v7/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/v7/go/gcp/organizations"
    	"github.com/pulumi/pulumi-gcp/sdk/v7/go/gcp/serviceaccount"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    
    func main() {
    	pulumi.Run(func(ctx *pulumi.Context) error {
    		_, err := organizations.GetClientConfig(ctx, nil, 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, nil, 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();
    
            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();
    
            ctx.export("target-email", me.applyValue(getClientOpenIdUserInfoResult -> getClientOpenIdUserInfoResult.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 lifetime of 3600 seconds.

    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)
    // Output-based functions aren't available in Java yet
    
    fn::invoke:
      function: gcp:serviceaccount/getAccountAccessToken:getAccountAccessToken
      arguments:
        # arguments dictionary

    The following arguments are supported:

    Scopes List<string>
    The scopes the new credential should have (e.g. ["cloud-platform"])
    TargetServiceAccount string
    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"])
    TargetServiceAccount string
    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"])
    targetServiceAccount String
    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"])
    targetServiceAccount string
    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_account str
    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"])
    targetServiceAccount String
    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_token representing the new generated identity.
    Id string
    The provider-assigned unique ID for this managed resource.
    Scopes List<string>
    TargetServiceAccount string
    Delegates List<string>
    Lifetime string
    AccessToken string
    The access_token representing the new generated identity.
    Id string
    The provider-assigned unique ID for this managed resource.
    Scopes []string
    TargetServiceAccount string
    Delegates []string
    Lifetime string
    accessToken String
    The access_token representing the new generated identity.
    id String
    The provider-assigned unique ID for this managed resource.
    scopes List<String>
    targetServiceAccount String
    delegates List<String>
    lifetime String
    accessToken string
    The access_token representing the new generated identity.
    id string
    The provider-assigned unique ID for this managed resource.
    scopes string[]
    targetServiceAccount string
    delegates string[]
    lifetime string
    access_token str
    The access_token representing the new generated identity.
    id str
    The provider-assigned unique ID for this managed resource.
    scopes Sequence[str]
    target_service_account str
    delegates Sequence[str]
    lifetime str
    accessToken String
    The access_token representing the new generated identity.
    id String
    The provider-assigned unique ID for this managed resource.
    scopes List<String>
    targetServiceAccount String
    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-beta Terraform Provider.
    gcp logo
    Google Cloud Classic v7.28.0 published on Friday, Jun 21, 2024 by Pulumi