All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:Jun 21, 2026

The Alibaba Cloud SDK uses the Credentials tool to centrally manage credentials, such as your AccessKey and STS Token. This topic describes the supported credential types and their configuration methods.

Background

A credential is a set of information that verifies a user's identity. To sign in to a system, a user must provide valid credentials. Common credential types include:

  1. An AccessKey is a long-term credential for an Alibaba Cloud account or a RAM user. It is a key pair composed of an AccessKey ID and an AccessKey secret.

  2. An STS token is a temporary access credential for a RAM role. It includes a configurable validity period and access permissions. For more information, see What is STS.

  3. A bearer token is a credential used for authentication and authorization.

Prerequisites

Install Alibaba Cloud Credentials

If Alibaba Cloud Credentials is already installed, you can skip this step. We recommend using the latest Alibaba Cloud Credentials dependency to ensure full support for all credential types. For information about all released versions, see Alibaba Cloud Credentials.

You can install Alibaba Cloud Credentials using one of the following methods:

  • Method 1: Use go get to install Alibaba Cloud Credentials:

    $ go get -u github.com/aliyun/credentials-go
  • Method 2: If you use dep to manage dependencies, run the following command:

    dep ensure -add github.com/aliyun/credentials-go

Credentials tool: Parameters

The Config struct in the github.com/aliyun/credentials-go/credentials package defines the configuration parameters for the credentials tool. Use the required type parameter to specify the credential type, then configure the parameters for that type. The following table lists the valid values for the type parameter and the parameters that each credential type supports. In this table, indicates a required parameter, - indicates an optional parameter, and × means the parameter is not supported.

Note

Avoid using credential types or parameters not listed in the table below.

Type

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

AccessKeyId: The AccessKey ID.

×

×

×

×

AccessKeySecret: The AccessKey secret.

×

×

×

×

SecurityToken: The STS token.

×

-

×

×

×

×

RoleArn: The Alibaba Cloud Resource Name (ARN) of the RAM role.

×

×

×

×

×

RoleSessionName: The custom session name. The default format is credentials-go-<timestamp>.

×

×

-

×

-

×

×

RoleName: The RAM role name.

×

×

×

-

×

×

×

DisableIMDSv1: Set to true to enforce the security hardening mode. The default value is false.

×

×

×

-

×

×

×

BearerToken: The bearer token.

×

×

×

×

×

×

Policy: The custom policy.

×

×

-

×

-

×

×

RoleSessionExpiration: The session expiration time, in seconds. The default value is 3,600.

×

×

-

×

-

×

×

OIDCProviderArn: The Alibaba Cloud Resource Name (ARN) of the OpenID Connect (OIDC) identity provider (IdP).

×

×

×

×

×

×

OIDCTokenFilePath: The path to the OIDC token file.

×

×

×

×

×

×

ExternalId: The external ID of the role. This ID helps prevent the confused deputy issue. For more information, see Use ExternalId to prevent the confused deputy issue.

×

×

-

×

×

×

×

Url: The URI of the credential. This value is set by using the SetURLCredential(v string) method.

×

×

×

×

×

×

STSEndpoint: The STS endpoint. This parameter supports both VPC and public endpoints. For a list of valid values, see Endpoints. The default is sts.aliyuncs.com.

×

×

-

×

-

×

×

Timeout: The HTTP read timeout, in milliseconds. The default value is 5,000.

×

×

-

-

-

-

×

ConnectTimeout: The HTTP connection timeout, in milliseconds. The default value is 10,000.

×

×

-

-

-

-

×

Initialize a credentials client

The previous section describes the credential types and configuration parameters supported by the Credentials tool. The following sections provide code examples showing how to use the tool. Select the method that best fits your scenario.

Important
  • Hard-coding an AccessKey in your project creates security risks. Improperly managed repository permissions can expose all resources in your account. It is recommended to store the AccessKey in environment variables or configuration files.

  • Use a singleton pattern with the Credentials tool. This pattern enables the tool's built-in credential caching to prevent rate limiting from frequent API calls and avoid resource waste from creating multiple instances. For more information, see Automatic refresh of session credentials.

Method 1: using the default credential provider chain

B{Credential file exists?}; B -- Yes --> C(Read credential file); B -- No --> D{Environment variables configured?}; C --> E{Valid credential obtained?}; D -- Yes --> F(Read environment variables); D -- No --> G{ECS instance used?}; F --> E; G -- Yes --> H(Read instance RAM role); G -- No --> I(Error returned); H --> E; E -- Yes --> J(Valid credential obtained); E -- No --> I; J --> K(END); I --> L(END); ]]>

If you initialize the Credentials client without parameters, Credentials uses the default credential provider chain. To learn more about how the default credentials are loaded, see Default credential provider chain.

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Pass nil to use the default credential provider chain.
	credential, err := credentials.NewCredential(nil)
	config := &openapi.Config{}
        config.Credential = credential
        // The code to initialize a cloud product client is omitted. See the API call example for details.
}

API call example

This example shows how to call the DescribeRegions operation of ECS. To run this example, install the ECS SDK for Go.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Create a credential from the default provider chain.
	credentialClient, _err := credentials.NewCredential(nil)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Set the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Set the credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation and get the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Method 2: AccessKey

The Credentials tool uses the AccessKey you provide as the access credential.

Warning

An Alibaba Cloud account (root account) has full permissions over all its resources, so an exposed AK poses a significant security risk. Do not use the AK of a root account.

Use the AK of a RAM user with least-privilege permissions.

package main
import (
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("access_key").
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
	akCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
	config.Credential = akCredential
	// Code to initialize a cloud product client is omitted. See the API call example for details.
}

API example

This example shows how to call the DescribeRegions operation of ECS. To run this example, you must first install the ECS SDK.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	// Initialize the credential client with an AccessKey pair.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("access_key").
		// Set your AccessKey ID.
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		// Set your AccessKey secret.
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Configure the credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize a DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Method 3: STS token

The Credentials tool uses the static STS token you provide as the access credential.

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("sts").
		// Get the AccessKey ID from the environment variable.
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		// Get the AccessKey secret from the environment variable.
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
		// Get the security token from the environment variable.
		SetSecurityToken(os.Getenv("ALIBABA_CLOUD_SECURITY_TOKEN"))
	stsCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
        config.Credential = stsCredential
        // The initialization code for the cloud product client is omitted. For details, see the API call examples.
}

API call

This example shows how to call the DescribeRegions operation of ECS. To run this example, install the ECS SDK and the STS SDK.

package main
import (
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	sts20150401 "github.com/alibabacloud-go/sts-20150401/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Create an STS client and call the AssumeRole operation to obtain an STS token.
	stsConfig := &openapi.Config{}
	stsConfig.SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
	stsConfig.SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
	stsConfig.SetEndpoint("sts.cn-hangzhou.aliyuncs.com")
	client, _err := sts20150401.NewClient(stsConfig)
	if _err != nil {
		panic(_err)
	}
	assumeRoleRequest := &sts20150401.AssumeRoleRequest{}
	// The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set RoleArn by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
	assumeRoleRequest.SetRoleArn("<RoleArn>")
	// The role session name. You can set RoleSessionName by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
	assumeRoleRequest.SetRoleSessionName("<RoleSessionName>")
	assumeRoleRequest.SetDurationSeconds(3600)
	result, _err := client.AssumeRole(assumeRoleRequest)
	if _err != nil {
		panic(_err)
	}
	assumeRoleResponseBodyCredentials := result.Body.Credentials
	// Use an STS token to initialize the Credentials client.
	credentialsConfig := new(credentials.Config).
		// Specify the credential type.
		SetType("sts").
		SetAccessKeyId(*assumeRoleResponseBodyCredentials.AccessKeyId).
		SetAccessKeySecret(*assumeRoleResponseBodyCredentials.AccessKeySecret).
		SetSecurityToken(*assumeRoleResponseBodyCredentials.SecurityToken)
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-hangzhou.aliyuncs.com")
	// Configure the credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation and retrieve the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Method 4: AK and RamRoleArn

This method uses an STS token internally. By specifying the ARN (Alibaba Cloud Resource Name) of a RAM role, the credentials tool obtains an STS token from STS. You can also use SetPolicy to restrict the RAM role to a smaller permission set.

package main
import (
	"fmt"
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("ram_role_arn").
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
		// Specifies the ARN of the RAM role to assume, such as `acs:ram::123456789012****:role/adminrole`. You can also set this with the `ALIBABA_CLOUD_ROLE_ARN` environment variable.
		SetRoleArn("<RoleArn>").
		// A custom name for the role session. You can also set this with the `ALIBABA_CLOUD_ROLE_SESSION_NAME` environment variable.
		SetRoleSessionName("<RoleSessionName>").
		// Optional. An inline policy that further restricts the permissions of the temporary credentials. For example, `{"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}`
		SetPolicy("<Policy>").
		// Optional. The session expiration time in seconds.
		SetRoleSessionExpiration(3600).
		// Optional. The external ID used to prevent the confused deputy problem.
		SetExternalId("ExternalId").
		// Optional. The STS endpoint. The default is sts.aliyuncs.com. For better network performance, use a region-specific endpoint closer to your application.
		SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com")
	arnCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
        config.Credential = arnCredential
        // This example omits the client initialization code. For more information, see the API call example.
}
Note

To learn more about the external ID, see Prevent the confused deputy problem with external IDs.

API example

This example shows how to call the DescribeRegions operation of ECS. To run this example, install the ECS SDK.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	// Initialize the credential configuration with a RAM role ARN.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("ram_role_arn").
		// The AccessKey ID.
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		// The AccessKey Secret.
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
		// The ARN of the RAM role to assume. This can be set with the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
		SetRoleArn("<RoleArn>").
		// A custom name for the role session. This can be set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
		SetRoleSessionName("<RoleSessionName>").
		// Optional. An inline policy to further restrict permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
		SetPolicy("<Policy>").
		// Optional. The session expiration time in seconds.
		SetRoleSessionExpiration(3600).
		// Optional. The STS endpoint. The default is sts.aliyuncs.com. For better network performance, use a region-specific endpoint closer to your application.
		SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com")
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Assign the created credential to the ECS configuration.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation and retrieve the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Method 5: ECS instance RAM role

You can attach an instance RAM role to ECS and ECI instances. Applications on these instances can then use the credentials tool to automatically obtain an STS token to initialize the credentials client.

By default, the credentials tool accesses the ECS metadata server in security hardening mode (IMDSv2). On error, the tool automatically falls back to normal mode to obtain the access credential. You can control this fallback behavior by setting the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable:

  • If set to false (the default), the tool falls back to normal mode.

  • If set to true, the tool uses only security hardening mode and throws an exception on failure.

IMDSv2 support depends on the server configuration.

Additionally, you can disable credential access through ECS instance metadata by setting the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable.

Note
package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func _main(args []*string) {
	// Initialize a credentials client using an ECS RAM role.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("ecs_ram_role").
		// Optional. The name of the ECS RAM role. If left empty, the name is automatically retrieved. Set this parameter to reduce API calls. You can also set it using the ALIBABA_CLOUD_ECS_METADATA environment variable.
		SetRoleName("<RoleName>")
	// Optional, defaults to false. A value of `true` enforces security hardening mode (IMDSv2). When set to `false`, the SDK first attempts to retrieve credentials in security hardening mode and falls back to normal mode (IMDSv1) if the attempt fails.
	// credentialsConfig.SetDisableIMDSv1(true)
	credentialClient, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
        config.Credential = credentialClient
        // The code to initialize a cloud product client with this config object is omitted. For details, see the API call example.
}

API call example

This example shows how to call the DescribeRegions operation of ECS. You must install the ECS SDK before running the example.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Initialize the Credentials client by using an ECS RAM role.
	credentialsConfig := new(credentials.Config).
		// Specifies the credential type.
		SetType("ecs_ram_role").
		// Optional. The role name. If omitted, the name is automatically retrieved. Specifying this parameter is recommended to reduce requests. You can also set the role name by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
		SetRoleName("<RoleName>")
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Sets the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Sets the client credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize the runtime configuration.
	runtime := &util.RuntimeOptions{}
	// Calls the DescribeRegions operation and retrieves the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Method 6: Use OIDCRoleArn

If you use OIDC for authentication and have created a RAM role for an OIDC identity provider, you can provide the OIDC provider ARN, OIDC token file path, and RAM role ARN to the Credentials tool. The tool then automatically calls the AssumeRoleWithOIDC API to obtain an STS token for the RAM role, which is used as the access credential. Credentials obtained this way support automatic refresh. For more information, see Automatic refresh of session credentials. For example, if your application runs in a Container Service for Kubernetes (ACK) cluster with RRSA enabled, the Credentials tool can read the OIDC configuration from the pod's environment variables and call the AssumeRoleWithOIDC API to obtain an STS token. You can then use this STS token to access Alibaba Cloud services.

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.comcom/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("oidc_role_arn").
		// The OIDC provider ARN. You can set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
		SetOIDCProviderArn(os.Getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN")).
		// The OIDC token file path. You can set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
		SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
		// The RAM role ARN. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
		SetRoleArn(os.Getenv("ALIBABA_CLOUD_ROLE_ARN")).
		// The role session name. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
		SetRoleSessionName(os.Getenv("ALIBABA_CLOUD_ROLE_SESSION_NAME")).
		// Optional. Specifies an inline policy to further restrict permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
		SetPolicy("<Policy>").
		// Optional. Specifies the session expiration in seconds.
		SetRoleSessionExpiration(3600).
		// Optional. The STS endpoint. The default is sts.aliyuncs.com. For improved network connectivity, use a region-specific endpoint.
		SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com")
	oidcCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
	config.Credential = oidcCredential
	// Code for initializing a cloud product client with the config object is omitted. For more information, see the API call example.
}

API example

This example shows how to call the ECS DescribeRegions operation. To run this code, you must install the ECS SDK for Go.

package main
import (
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Initialize the Credentials client by using an OIDC Role ARN.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("oidc_role_arn").
		// The ARN of the OIDC identity provider. Set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
		SetOIDCProviderArn(os.Getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN")).
		// The file path of the OIDC token. Set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
		SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
		// The ARN of the RAM role. Set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
		SetRoleArn(os.Getenv("ALIBABA_CLOUD_ROLE_ARN")).
		// The role session name. Set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
		SetRoleSessionName(os.Getenv("ALIBABA_CLOUD_ROLE_SESSION_NAME")).
		// Optional. An inline policy that further restricts permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
		SetPolicy("<Policy>").
		// The session duration in seconds.
		SetRoleSessionExpiration(3600)
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Assign the credential to the client configuration.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize the runtime configuration.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Method 7: Use a URI credential

You can encapsulate the Security Token Service (STS) behind a service URI, allowing external services to obtain an STS token without exposing sensitive information like AKs. The Credentials tool can then use this URI to fetch an STS token to use as the access credential. Credentials obtained this way support automatic refresh. For more information, see Automatic refresh of session credentials.

package main
import (
	"github.com/aliyun/credentials-go/credentials"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("credentials_uri").
                // The credential URI. Format: http://local_or_remote_uri/. You can also set this by using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
		SetURLCredential("<CredentialsUri>")
	uriCredential, err := credentials.NewCredential(credentialsConfig)
	config := &openapi.Config{}
	config.Credential = uriCredential
	// The client initialization code for the cloud product is omitted for brevity. For more information, see the API call example.
}

The URI must conform to the following:

  • Supports GET requests.

  • The response body has the following structure:

    {
      "AccessKeySecret": "AccessKeySecret",
      "AccessKeyId": "AccessKeyId",
      "Expiration": "2021-09-26T03:46:38Z",
      "SecurityToken": "SecurityToken"
    }

API example

This example shows how to call the DescribeRegions operation of ECS. Running this example requires the ECS SDK for Go.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func main() {
	config := new(credentials.Config).
		SetType("credentials_uri").
		// The credential URI, for example, http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
		SetURLCredential("<CredentialsUri>")
	uriCredential, _err := credentials.NewCredential(config)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Configure the credential.
	ecsConfig.Credential = uriCredential
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize the runtime configuration.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Method 8: Use bearer token

Only Cloud Call Center (CCC) supports initializing credentials with a bearer token.

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("bearer").
		// Enter your bearer token.
		SetBearerToken("<BearerToken>")
	bearerCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
	config.Credential = bearerCredential
	// This example omits the client initialization code. See the API call example for the complete implementation.
}

API example

This example shows how to call the GetInstance operation of Cloud Call Center. To run this example, first install the CCC SDK.

package main
import (
	ccc20200701 "github.com/alibabacloud-go/ccc-20200701/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func _main() (_err error) {
	// Initialize the credential client by using a bearer token.
	credentialsConfig := new(credentials.Config).
		// Specify the credential type.
		SetType("bearer").
		SetBearerToken("<BearerToken>")
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		return _err
	}
	// Initialize the CCC client with the credential client.
	config := &openapi.Config{}
	config.Endpoint = tea.String("ccc.cn-shanghai.aliyuncs.com") // Specify the service endpoint.
	config.Credential = credentialClient                         // Configure the credential.
	cccClient, _err := ccc20200701.NewClient(config)
	if _err != nil {
		return _err
	}
	getInstanceRequest := &ccc20200701.GetInstanceRequest{
		InstanceId: tea.String("ccc-test"),
	}
	runtime := &util.RuntimeOptions{}
	response, _err := cccClient.GetInstanceWithOptions(getInstanceRequest, runtime)
	if _err != nil {
		return _err
	}
	panic(response.Body.String())
}
func main() {
	err := _main()
	if err != nil {
		panic(err)
	}
}

Method 9: Use CLIProfileCredentialsProvider

Retrieves access credentials from the Alibaba Cloud CLI credential configuration file, config.json.

package main
import (
	"github.com/aliyun/credentials-go/credentials"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials/providers"
)
func main() {
	// CLIProfileCredentialsProvider
	provider, err := providers.NewCLIProfileCredentialsProviderBuilder().
	        // Optional. Specifies the profile name. The resolution precedence is: explicit profileName > ALIBABA_CLOUD_CONFIG_FILE environment variable > 'current' profile in config.json.
		WithProfileName("<PROFILE_NAME>"). 
		// Optional. Specifies the path to the configuration file (which must be a .json file). The resolution precedence is: the specified profileFile > the ALIBABA_CLOUD_CONFIG_FILE environment variable > the default path ~/.aliyun/config.json.
		WithProfileFile("<PROFILE_FILE_PATH>"). 
		Build()
	if err != nil {
		return
	}
	credential := credentials.FromCredentialsProvider("cli_profile", provider)
	config := &openapi.Config{}
	config.Credential = credential
	// The code for initializing a cloud product client with the config object is omitted for brevity.
}

You can configure credentials by using the Alibaba Cloud CLI, or manually create the config.json configuration file in the following path:

  • Linux: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

The file content must be in the following format:

{
  "current": "<PROFILE_NAME>",
  "profiles": [
    {
      "name": "<PROFILE_NAME>",
      "mode": "AK",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
    },
    {
      "name": "<PROFILE_NAME1>",
      "mode": "StsToken",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "sts_token": "<SECURITY_TOKEN>"
    },
    {
      "name":"<PROFILE_NAME2>",
      "mode":"RamRoleArn",
      "access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME3>",
      "mode":"EcsRamRole",
      "ram_role_name":"<RAM_ROLE_ARN>"
    },
    {
      "name":"<PROFILE_NAME4>",
      "mode":"OIDC",
      "oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
      "oidc_token_file":"<OIDC_TOKEN_FILE>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME5>",
      "mode":"ChainableRamRoleArn",
      "source_profile":"<PROFILE_NAME>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name": "<PROFILE_NAME6>",
      "mode": "CloudSSO",
      "cloud_sso_sign_in_url": "https://******/login",
      "access_token": "eyJraWQiOiJiYzViMzUwYy******",
      "cloud_sso_access_token_expire": 1754316142,
      "cloud_sso_access_config": "ac-00s1******",
      "cloud_sso_account_id": "151266******"
    }
  ]
}

In the config.json file, use the mode parameter to specify the credential type:

  • AK: Uses an Access Key.

  • StsToken: Uses an STS token.

  • RamRoleArn: Assumes a RAM role by using its ARN to obtain the credential.

  • EcsRamRole: Assumes the RAM role attached to an ECS instance to obtain the credential.

  • OIDC: Uses an OIDC provider ARN and an OIDC token to obtain the credential.

  • ChainableRamRoleArn: Uses a role chain, where source_profile is used to specify the name of other credentials in the config.json configuration file to retrieve new credentials.

  • CloudSSO: Uses the credential obtained by a Cloud SSO user through the Alibaba Cloud CLI.

    Note

    CloudSSO credentials require version 1.4.7 or later of github.com/aliyun/credentials-go, and the configuration can be obtained only by using the Alibaba Cloud CLI. For more information, see Use the CLI to log on to CloudSSO and access Alibaba Cloud resources.

After you complete the configuration, the provider initializes a credential based on the specified profile name.

API call example

This example shows how to call the ECS DescribeRegions operation. To run this example, you must first install the ECS SDK.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
	"github.com/aliyun/credentials-go/credentials/providers"
)
func main() {
	// CLIProfileCredentialsProvider
	provider, err := providers.NewCLIProfileCredentialsProviderBuilder().
		WithProfileName("SSOProfile"). // Optional. Defaults to 'current' in config.json.
		// WithProfileFile("/path/to/config.json"). // Optional. Defaults to ~/.aliyun/config.json.
		Build()
	if err != nil {
		return
	}
	credentialClient := credentials.FromCredentialsProvider("cli_profile", provider)
	// Use the credential to initialize the ECS client.
	ecsConfig := &openapi.Config{}
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	ecsConfig.Credential = credentialClient
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	runtime := &util.RuntimeOptions{}
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Default credential provider chain

When development and production environments require different types of credentials, it is common to write conditional code to retrieve credentials based on the current environment. The default credential provider chain simplifies this process, letting you use a single codebase and control credential retrieval through external configuration. When you initialize a credentials client by calling NewCredential() without any parameters, the Alibaba Cloud SDK searches for credentials in the following order.

1. Environment variables

If no credential is found in the system properties, the provider chain then checks for environment variables.

  • If both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are present and not empty, the provider chain uses them as the default credential.

  • If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are also set, the provider chain uses an STS token as the default credential.

2. OIDC RAM role

If no credential has been found, the provider chain checks for the following environment variables related to an OIDC RAM role:

  • ALIBABA_CLOUD_ROLE_ARN: The ARN of the RAM role.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: The ARN of the OIDC provider.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: The file path of the OIDC token.

If all three environment variables are present and not empty, the provider chain uses these values to call the AssumeRoleWithOIDC API of the Security Token Service (STS) to obtain an STS token.

3. config.json file

If no higher-precedence credentials are found, the Credentials tool loads the config.json file. The default paths for this file are as follows:

  • Linux/macOS: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

Note

Starting from version github.com/aliyun/credentials-go@1.4.4, you can customize the path to the config.json file by using the ALIBABA_CLOUD_CONFIG_FILE environment variable. This environment variable takes precedence over the default path.

To configure credentials with this method, you can use the Alibaba Cloud CLI or manually create a config.json file in the appropriate path. The following example shows the file format:

{
    "current": "<PROFILE_NAME>",
    "profiles": [
        {
            "name": "<PROFILE_NAME>",
            "mode": "AK",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
        },
        {
            "name": "<PROFILE_NAME1>",
            "mode": "StsToken",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
            "sts_token": "<SECURITY_TOKEN>"
        },
        {
            "name": "<PROFILE_NAME2>",
            "mode": "RamRoleArn",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
            "ram_role_arn": "<ROLE_ARN>",
            "ram_session_name": "<ROLE_SESSION_NAME>",
            "expired_seconds": 3600
        },
        {
            "name": "<PROFILE_NAME3>",
            "mode": "EcsRamRole",
            "ram_role_name": "<RAM_ROLE_ARN>"
        },
        {
            "name": "<PROFILE_NAME4>",
            "mode": "OIDC",
            "oidc_provider_arn": "<OIDC_PROVIDER_ARN>",
            "oidc_token_file": "<OIDC_TOKEN_FILE>",
            "ram_role_arn": "<ROLE_ARN>",
            "ram_session_name": "<ROLE_SESSION_NAME>",
            "expired_seconds": 3600
        },
        {
            "name": "<PROFILE_NAME5>",
            "mode": "ChainableRamRoleArn",
            "source_profile": "<PROFILE_NAME>",
            "ram_role_arn": "<ROLE_ARN>",
            "ram_session_name": "<ROLE_SESSION_NAME>",
            "expired_seconds": 3600
        },
        {
            "name": "<PROFILE_NAME6>",
            "mode": "CloudSSO",
            "cloud_sso_sign_in_url": "https://******/login",
            "access_token": "eyJraWQiOiJiYzViMzUwYy******",
            "cloud_sso_access_token_expire": 1754316142,
            "cloud_sso_access_config": "ac-00s1******",
            "cloud_sso_account_id": "151266******"
        },
        {
            "name": "<PROFILE_NAME7>",
            "mode": "OAuth",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
            "sts_token": "<SECURITY_TOKEN>",
            "region_id": "<REGION_ID>",
            "output_format": "json",
            "language": "<zh|en>",
            "sts_expiration": "<STS_EXPIRATION>",
            "oauth_access_token": "<OAUTH_ACCESS_TOKEN>",
            "oauth_refresh_token": "<OAUTH_REFRESH_TOKEN>",
            "oauth_access_token_expire": 1754316142,
            "oauth_site_type": "<CN|EN>"
        }
    ]
}

In the config.json file, you can use the mode parameter to specify different credential types:

  • AK: Uses a user's access key as credentials.

  • StsToken: Uses an STS token as credentials.

  • RamRoleArn: Uses a RAM role ARN to obtain credentials.

  • EcsRamRole: Uses the RAM role attached to an ECS instance to obtain credentials.

  • OIDC: Uses an OIDC provider ARN and an OIDC token to obtain credentials.

  • ChainableRamRoleArn: Implements a role chain. Use the source_profile parameter to specify another profile in the config.json file from which to obtain new credentials.

  • OAuth: Uses credentials obtained by logging in through OAuth by using the Alibaba Cloud CLI.

  • CloudSSO: Uses credentials obtained by a CloudSSO user through the Alibaba Cloud CLI.

Note

After configuration, Credentials initializes the client by using the profile specified in the current field of the configuration file. You can also specify a profile by setting the ALIBABA_CLOUD_PROFILE environment variable. For example, set the value of ALIBABA_CLOUD_PROFILE to client1.

4. ECS instance RAM role

If no higher-precedence credentials are found, Credentials obtains them from the RAM role attached to an ECS instance. By default, Credentials uses IMDSv2 to access the ECS metadata service and retrieve an STS token for the ECS instance RAM role. This process involves two requests: the first to get the role name from the metadata service, and the second to retrieve the credentials. To reduce this to a single request, you can specify the instance RAM role name directly by setting the ALIBABA_CLOUD_ECS_METADATA environment variable. If an error occurs while using IMDSv2, Credentials automatically falls back to IMDSv1. You can control this fallback behavior by setting the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable:

  1. When set to false, the tool falls back to IMDSv1 to retrieve credentials if the IMDSv2 request fails.

  2. When set to true, the tool only uses IMDSv2. If the request fails, an exception is thrown.

Whether the server supports IMDSv2 depends on your server configuration.

You can also disable credential access from the ECS metadata service by setting the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable.

Note

5. Credentials URI

If no credential has been found, the provider chain checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable is set and points to a valid URI, the chain accesses the URI to retrieve an STS token.

Automatic session credential refresh

Session credential types, such as ram_role_arn, ecs_ram_role, oidc_role_arn, and credentials_uri, support automatic refresh through a built-in mechanism in the credential provider. When a credential client retrieves a credential for the first time, the provider stores it in a cache. In subsequent operations, the same client instance automatically retrieves the credential from this cache. If the cached credential has expired, the client instance fetches a new one and updates the cache accordingly.

Note

For ecs_ram_role credentials, the credential provider proactively refreshes them 15 minutes before they expire.

The following example uses the singleton pattern to create a credential client. It demonstrates the refresh mechanism by fetching a credential at different time intervals and calling an OpenAPI operation to verify that the credential is usable.

package main
import (
	"fmt"
	"log"
	"os"
	"sync"
	"time"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.comcom/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
)
// Credential manages the singleton instance of Alibaba Cloud credentials.
type Credential struct {
	instance credentials.Credential
	once     sync.Once
}
var credentialInstance = &Credential{}
func GetCredentialInstance() credentials.Credential {
	credentialInstance.once.Do(func() {
		cfg := &credentials.Config{
			Type:                  tea.String("ram_role_arn"),
			AccessKeyId:           tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
			AccessKeySecret:       tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
			RoleArn:               tea.String(os.Getenv("ALIBABA_CLOUD_ROLE_ARN")),
			RoleSessionName:       tea.String("RamRoleArnTest"),
			RoleSessionExpiration: tea.Int(3600),
		}
		var err error
		credentialInstance.instance, err = credentials.NewCredential(cfg)
		if err != nil {
			log.Fatalf("Credential initialization failed: %v", err)
		}
	})
	return credentialInstance.instance
}
// EcsClient manages the singleton instance of the ECS client.
type EcsClient struct {
	instance *ecs20140526.Client
	once     sync.Once
}
var ecsClientInstance = &EcsClient{}
func GetEcsClientInstance(cred credentials.Credential) *ecs20140526.Client {
	ecsClientInstance.once.Do(func() {
		cfg := &openapi.Config{
			Endpoint:   tea.String("ecs.cn-hangzhou.aliyuncs.com"),
			Credential: cred,
		}
		var err error
		ecsClientInstance.instance, err = ecs20140526.NewClient(cfg)
		if err != nil {
			log.Fatalf("ECS client initialization failed: %v", err)
		}
	})
	return ecsClientInstance.instance
}
// Run the main task.
func runTask() {
	cred := GetCredentialInstance()
	credentialModel, err := cred.GetCredential()
	if err != nil {
		log.Printf("Failed to get credential: %v", err)
		return
	}
	fmt.Println(time.Now())
	fmt.Printf("AK ID: %s, AK Secret: %s, STS Token: %s\n",
		*credentialModel.AccessKeyId,
		*credentialModel.AccessKeySecret,
		*credentialModel.SecurityToken)
	ecsClient := GetEcsClientInstance(cred)
	req := &ecs20140526.DescribeRegionsRequest{}
	runtime := &util.RuntimeOptions{}
	resp, err := ecsClient.DescribeRegionsWithOptions(req, runtime)
	if err != nil {
		log.Printf("ECS API call failed: %v", err)
		return
	}
	fmt.Printf("Invoke result: %d\n", *resp.StatusCode)
}
func main() {
	done := make(chan bool)
	// Start a goroutine to run scheduled tasks.
	go func() {
		tick := time.NewTicker(1 * time.Second)
		defer tick.Stop()
		executionCount := 0
		delays := []time.Duration{0, 600, 3600, 100} // Delay in seconds.
		for {
			select {
			case <-tick.C:
				if executionCount < len(delays) {
					delay := delays[executionCount]
					time.Sleep(delay * time.Second)
					runTask()
					executionCount++
				} else {
					close(done)
					return
				}
			}
		}
	}()
	<-done
	fmt.Println("All tasks completed. Exiting...")
}
2025-05-29 10:56:24.7142698 +0800 CST m=+1.418627901
AK ID: STS.NXFN xxx 33d7Da, AK Secret: 3QdoQASHSyt xxx UGNjZaHsEGXZXc, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5vZBf3Biotj1o6MQGjFgTI2eLwfi/Lvgzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7VsDs194Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx m5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAvw3VhNiQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx D2hT+Bi3HLQztLtlrnMQdpz0agAFDeioHfrugVbFZyY9ggw28Pyx4ckcndsp1cWIU/kwT5HYClH6X7ArciY+H1V01Nh1W7dDFIiwn5htgzQkn1K2xXKA1SNzCjy076rXe7F+BNGES3mUPuTTk
irb467Kb6f3SHj7 xxx J6DPHSj/VzDSAA
Invoke result: 200
2025-05-29 11:06:25.3225563 +0800 CST m=+602.026914401
AK ID: STS.NXFN xxx 33d7Da, AK Secret: 3QdoQASHSyt xxx UGNjZaHsEGXZXc, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5vZBf3Biotj1o6MQGjFgTI2eLwfi/Lvgzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7VsDs194Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx m5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAvw3VhNiQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx D2hT+Bi3HLQztLtlrnMQdpz0agAFDeioHfrugVbFZyY9ggw28Pyx4ckcndsp1cWIU/kwT5HYClH6X7ArciY+H1V01Nh1W7dDFIiwn5htgzQkn1K2xXKA1SNzCjy076rXe7F+BNGES3mUPuTTk
irb467Kb6f3SHj7 xxx J6DPHSj/VzDSAA
Invoke result: 200
2025-05-29 12:06:26.039859 +0800 CST m=+4202.744217101
AK ID: STS.NWDS xxx 73kVg5u, AK Secret: C3tJCLkszB3 xxx PHGcUroGruw8D, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5TxGOKBjrYY1ZCEWmrFr2YUO7xHuaKelzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7Vtz5F96Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx 5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAsQnUp9tQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx 2hT+Bi3HLQztcMoybMQdpz0agAExoac2PSXrXSXyh4J+ekl0xNIztOFEAJJ2qTkuUgP1AKZIsZYdnX+yHJ1XJpD/yd6pKCEmUSzBwR+Q+S1BmhDANmVRzwUG8QJwxD6bTEvjUwhpGUOKLJL6b
FoBpJJ4WDZRliiw0 xxx y8sGj81a/iiAA
Invoke result: 200
2025-05-29 12:08:06.3556621 +0800 CST m=+4303.060020201
AK ID: STS.NWDS xxx 73kVg5u, AK Secret: C3tJCLkszB3 xxx PHGcUroGruw8D, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5TxGOKBjrYY1ZCEWmrFr2YUO7xHuaKelzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7Vtz5F96Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx 5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAsQnUp9tQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx 2hT+Bi3HLQztcMoybMQdpz0agAExoac2PSXrXSXyh4J+ekl0xNIztOFEAJJ2qTkuUgP1AKZIsZYdnX+yHJ1XJpD/yd6pKCEmUSzBwR+Q+S1BmhDANmVRzwUG8QJwxD6bTEvjUwhpGUOKLJL6b
FoBpJJ4WDZRliiw0 xxx y8sGj81a/iiAA
Invoke result: 200
All tasks completed. Exiting...

Analysis based on the log output:

  • On the first call, the cache is empty. The system retrieves a credential based on your configuration and then stores it in the cache.

  • The second call uses the same credential as the first, indicating it was retrieved from the cache.

  • On the third call, the cached credential has expired. Its expiration time (RoleSessionExpiration) is 3,600 seconds, but this call is made 4,200 seconds after the first one. Consequently, the SDK's automatic refresh mechanism fetches a new credential and updates the cache.

  • The fourth call uses the same credential as the third, confirming that the cache was updated.

Related documents