Manage access credentials
When using the Alibaba Cloud SDK, the Credentials tool centrally manages your credentials, such as AccessKey and STS Token. This topic explains the supported credential types and how to configure them so you can get started quickly.
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:
-
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.
-
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.
-
A bearer token is a credential used for authentication and authorization.
Prerequisites
-
The credentials tool requires Go 1.10.x or later.
-
You must use V2.0 of the Alibaba Cloud SDK. For more information, see Use the Alibaba Cloud Go SDK with an IDE.
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 getto install Alibaba Cloud Credentials:$ go get -u github.com/aliyun/credentials-go -
Method 2: If you use
depto 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.
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 |
× |
× |
- |
× |
- |
× |
× |
|
RoleName: The RAM role name. |
× |
× |
× |
- |
× |
× |
× |
|
DisableIMDSv1: Set to true to enforce the security hardening mode. The default value is |
× |
× |
× |
- |
× |
× |
× |
|
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 |
× |
× |
- |
× |
- |
× |
× |
|
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 preceding sections described the credential types and configuration parameters for the credentials tool. The following code examples illustrate how to use them, helping you choose the best approach for your scenario.
-
Storing your AccessKey in plaintext can expose it through misconfigured code repository permissions, compromising all resources in your account. We recommend storing the AccessKey in an environment variable or a configuration file.
-
When using the Credentials tool, we recommend adopting the singleton pattern. This practice enables the tool's built-in credential cache, which prevents API throttling due to frequent calls and avoids wasting resources on multiple instances. For more information, see Automatic refresh mechanism for Session credentials.
Method 1: using the default credential provider chain
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
Method 2: AccessKey
The Credentials tool uses your AccessKey for access.
The root user of an Alibaba Cloud account has full permissions to all resources. If the AK for this root user is compromised, it poses a significant security risk. Therefore, avoid using the root user's AK.
As a best practice, use an AK from a least-privileged RAM user.
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
Method 3: STS token
The Credentials tool uses your static STS Token as an 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
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.
}
To learn more about the external ID, see Prevent the confused deputy problem with external IDs.
API example
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.
-
Using security hardening mode to obtain an STS token requires
credentials-goversion 1.3.10 or later. -
For more information about ECS instance metadata, see Instance metadata.
-
To grant a RAM role to an ECS or ECI instance, see Step 1: Create a RAM role and Grant an instance RAM role to an ECI instance.
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
Method 6: Use OIDCRoleArn
If you use the OIDC authentication protocol and have created a RAM role for an OIDC identity provider, pass the OIDC identity provider ARN, OIDC Token, and RAM role ARN to the credentials tool. The tool automatically calls the AssumeRoleWithOIDC operation to obtain an STS token for the RAM role and uses it as an access credential. These credentials support automatic refresh. For more information, see Automatic refresh of session-based credentials. For example, in an ACK cluster with RRSA enabled, the credentials tool reads the OIDC configuration from the pod's environment variables. It then calls the AssumeRoleWithOIDC operation to obtain an STS token for the service role, which allows your application 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
Method 7: Use a URI credential
By wrapping the STS service and exposing a URI, external services can retrieve an STS token to avoid exposing an AK. The credentials tool accesses the URI you provide to retrieve the STS token and uses it as an access credential. These credentials support auto-refresh. For more information, see session-type credential auto-refresh mechanism.
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
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
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_profileis used to specify the name of other credentials in theconfig.jsonconfiguration file to retrieve new credentials. -
CloudSSO: Uses the credential obtained by a Cloud SSO user through the Alibaba Cloud CLI.
NoteCloudSSO 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
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
The Credentials tool first checks the environment variables.
-
If ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are both set and not empty, they are used as the default credentials.
-
If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are all set and not empty, an STS token is used as the default credentials.
2. OIDC RAM role
If credentials have not been found, the Credentials tool checks for the following environment variables:
-
ALIBABA_CLOUD_ROLE_ARN: The RAM role ARN.
-
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: The OIDC provider ARN.
-
ALIBABA_CLOUD_OIDC_TOKEN_FILE: The file path of the OIDC token.
If all three of these environment variables are set and not empty, Credentials uses their values to call the AssumeRoleWithOIDC operation of the STS service to obtain an STS token. This token is then used as the default credentials.
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
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_profileparameter to specify another profile in theconfig.jsonfile 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.
-
OAuth credentials require
github.com/aliyun/credentials-goversion 1.4.8 or later. The configuration can only be obtained by using the Alibaba Cloud CLI. For more information, see Use the CLI to obtain OAuth credentials. -
CloudSSO credentials require
github.com/aliyun/credentials-goversion 1.4.7 or later. The configuration can only be obtained by using the Alibaba Cloud CLI. For more information, see Use Alibaba Cloud CLI to log on to CloudSSO and access Alibaba Cloud resources.
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:
-
When set to
false, the tool falls back to IMDSv1 to retrieve credentials if the IMDSv2 request fails. -
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.
-
For more information about ECS instance metadata, see Instance metadata.
-
For instructions on how to grant a RAM role to an ECS or ECI instance, see Step 1: Create a RAM role and Grant an instance RAM role to an ECI instance.
5. Credentials URI
If credentials are still not found, the Credentials tool checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable is set and points to a valid URI, Credentials accesses this URI to retrieve an STS token to use as the default credentials.
Automatic session credential refresh
The SDK automatically refreshes session credentials, such as ram_role_arn, ecs_ram_role, oidc_role_arn, and credentials_uri. When a credential client fetches a credential for the first time, the SDK caches it. The client then reuses the cached credential for subsequent requests. If the cached credential expires, the client automatically fetches a new one and updates the cache.
For ecs_ram_role type credentials, the SDK refreshes the credential 15 minutes before it expires.
This example demonstrates the automatic credential refresh mechanism. It uses the singleton pattern to create a credential client, fetches credentials at different time intervals, and calls an OpenAPI to verify their validity.
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...
-
During the first call, the SDK fetches a new credential because the cache is empty. The SDK then caches this credential.
-
The second call uses the same credential as the first, indicating it was retrieved from the cache.
-
The third call occurs 4,200 seconds after the first. Because the credential's expiration time (
RoleSessionExpiration) is 3,600 seconds, the cached credential has expired. The SDK then automatically fetches a new credential to replace the expired one in the cache. -
The fourth call uses the same new credential as the third call, showing that the cache was updated correctly.
References
-
For basic concepts about RAM, see Key concepts.
-
To create an AccessKey, see Create an AccessKey.
-
To programmatically create RAM users, AccessKeys, RAM roles, and permission policies, and to grant permissions, see RAM SDK overview.
-
To perform role assumption programmatically, see STS SDK overview.
-
For the RAM and STS API reference, see API reference.
-
Best practices for using access credentials to call Alibaba Cloud OpenAPI