All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:Jan 23, 2025

When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. This topic describes how to configure an access credential for Alibaba Cloud SDK V1.0 for Go. Access credentials improve access control when you use the SDK for development.

Background information

When you use Alibaba Cloud SDKs to perform development, configure a proper credential type based on your business scenario and permission control requirements. To help developers build a stable and reliable application, you must configure proper environment variables or configuration files to ensure that the SDK can read and use credentials.

Prerequisites

  • Go 1.10.x or later is used.

  • The core library of Alibaba Cloud SDK for Go is installed.

    go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk

Initialize a Credentials client

Method 1: Use the default credential provider chain

If you do not specify a method to initialize an SDK client, the default credential provider chain is used. For more information, see the Default credential provider chain section of this topic.

package main

import (
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
)

func main() {

    config := sdk.NewConfig()
    
    // No value is specified for this parameter.
    credential := credentials.NewDefaultCredentialsProvider()
    
    // <REGION_ID>: Specify the Alibaba Cloud region that the SDK client needs to access. Example: cn-hangzhou. 
    client, err := sdk.NewClientWithOptions("<REGION_ID>", config, credential)
    if err != nil {
	panic(err)
    }
    // The step of calling an API operation is omitted.
}

Method 2: Use an AccessKey pair

You can create an AccessKey pair for Alibaba Cloud accounts and Resource Access Management (RAM) users to call APIs. The AccessKey pair can be used to initialize an SDK client.

Important

An AccessKey pair of an Alibaba Cloud account has full access to all resources within the account. AccessKey pair leaks pose critical threats to the resources within an Alibaba Cloud account. We recommend that you use the AccessKey pair of a RAM user and regularly rotate the AccessKey pair. For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair.

package main

import (
    "os"

    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)

func main() {

    config := sdk.NewConfig()

    credential, err := credentials.NewStaticAKCredentialsProviderBuilder().
        // os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"): Obtain the AccessKey ID of the RAM user from an environment variable.
	WithAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
        // os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"): Obtain the AccessKey secret of the RAM user from an environment variable.
	WithAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
	Build()
    if err != nil {
	panic(err)
    }
    
    // <REGION_ID>: Specify the Alibaba Cloud region that the SDK client needs to access. Example: cn-hangzhou. 
    client, err := sdk.NewClientWithOptions("<REGION_ID>", config, credential)
    if err != nil {
	panic(err)
    }
    
    // The step of calling an API operation is omitted.
}

Method 3: Use an STS token

To ensure the security of your business, you can apply for temporary security credentials (TSC) from Security Token Service (STS) to create a temporary client.

package main

import (
    "os"

    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)

func main() {

    config := sdk.NewConfig()

    credential, err := credentials.NewStaticSTSCredentialsProviderBuilder().
        // os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"): Obtain the AccessKey ID of the RAM user from an environment variable.
	WithAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
	// os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"): Obtain the AccessKey secret of the RAM user from an environment variable.
	WithAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
        // os.Getenv("ALIBABA_CLOUD_SECURITY_TOKEN"): Obtain the STS token from the environment variable.	
	WithSecurityToken(os.Getenv("ALIBABA_CLOUD_SECURITY_TOKEN")).
	Build()
    if err != nil {
	panic(err)
    }
    
    // <REGION_ID>: Specify the Alibaba Cloud region that the SDK client needs to access. Example: cn-hangzhou. 
    client, err := sdk.NewClientWithOptions("<REGION_ID>", config, credential)
    if err != nil {
	panic(err)
    }
    
    // The step of calling an API operation is omitted.
}

Method 4: Use an AccessKey pair and a RAM role

You can specify the Alibaba Cloud Resource Name (ARN) of a RAM role to initialize an SDK client. The SDK client must obtain an STS token by calling the STS API before the client sends API requests. To limit permissions on an STS token, configure a custom policy in RAM.

package main

import (
    "os"

    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)

func main() {

    config := sdk.NewConfig()
    
    credential, err := credentials.NewRAMRoleARNCredentialsProviderBuilder().
        // os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"): Required. Obtain the AccessKey ID of the RAM user from the environment variable.
	WithAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
	// os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"): Required. Obtain the AccessKey secret of the RAM user from the environment variable.
	WithAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
	// "<Role_Arn>" Required. The ARN of the RAM role. You can obtain the ARN of a RAM role in the RAM console. Example: acs:ram::123456789012****:role/adminrole.
	WithRoleArn("<Role_Arn>").
	// "<ROLE_SESSION_NAME>" Required. The name of the role session, which is used to distinguish different sessions. Example: alice. 
	WithRoleSessionName("<ROLE_SESSION_NAME>").
	// "<POLICY>": Specify a custom policy to limit the role session permissions. Example: {\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}. 
	WithPolicy("<POLICY>").
	// "<EXTERNAL_ID>": Specify an external ID for the role, in case it is confused with the deputy. Example: abcd1234. 
	WithExternalId("<EXTERNAL_ID>").
	// <ROLE_SESSION_EXPIRATION>: the validity period of the token. Example: 3600. 
	WithDurationSeconds(3600).
	Build()
    if err != nil {
	panic(err)
    }
    
    // <REGION_ID>: Specify the Alibaba Cloud region that the SDK client needs to access. Example: cn-hangzhou.
    client, err := sdk.NewClientWithOptions("<REGION_ID>", config, credential)
    if err != nil {
	panic(err)
    }
    
    // The step of calling an API operation is omitted.
}

Method 5: Use the RAM role of an ECS instance

You can attach a RAM role to an ECS instance or elastic container instance. The Credentials tool automatically obtains the RAM role attached to the instance and uses the metadata server to obtain the STS token of the RAM role. The STS token is then used to initialize a Credentials client.

You can access instance metadata in normal or security hardening mode. By default, the Credentials tool obtains access credentials in security-hardening mode by using Instance Metadata Service Version 2 (IMDSv2). If an exception occurs in the security hardening mode, you can configure the DisableIMDSv1 parameter to specify an exception handling logic. Valid values of the DisableIMDSv1 parameter:

  1. If the parameter is set to false, which is the default value, the access credential is obtained in normal mode.

  2. true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode.

The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2).

Note
  • For more information about instance metadata, see Obtain instance metadata.

  • For more information about how to attach a RAM role to an ECS instance, see the "Create an instance RAM role and attach the instance RAM role to an ECS instance" section of the Instance RAM roles topic. For more information about how to attach a RAM role to an elastic container instance, see the "Assign the instance RAM role to an elastic container instance" section of the Use an instance RAM role by calling API operations topic.

package main

import (
    "os"

    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)

func main() {
    
    config := sdk.NewConfig()
    
    // Use an STS token to initialize an SDK client. The STS token is obtained by using the RAM role attached to an ECS instance.
    // This method is suitable for the programs that run on ECS instances and need to access other Alibaba Cloud resources.
   credential, err := credentials.NewECSRAMRoleCredentialsProviderBuilder().
	// "<ROLE_NAME>": Specify the name of the RAM role that you want to use. You can specify a default value for the roleName parameter in the environment variable ALIBABA_CLOUD_ECS_METADATA. Example: alice. 
	WithRoleName(os.Getenv("ALIBABA_CLOUD_ECS_METADATA")).
	// A value of true specifies that the security hardening mode is forcibly used. The default value is false, which specifies that the system first tries to obtain the access credential in security hardening mode. If the access credential fails to be obtained, the normal mode is used. 
	//WithDisableIMDSv1(true).
	Build()
    if err != nil {
	panic(err)
    }
    
   // <REGION_ID>: Specify the Alibaba Cloud region that the SDK client needs to access. Example: cn-hangzhou. 
   client, err := sdk.NewClientWithOptions("<REGION_ID>", config, credential)
   if err != nil {
	panic(err)
   }
   
   // The step of calling an API operation is omitted.
}

Method 6: Use the RAM role of an OIDC IdP

After you attach a RAM role to a worker node in an Container Service for Kubernetes (ACK) cluster, the pods on the worker node can use the metadata server to obtain an STS token. However, if you allow untrusted applications, such as applications whose code is not disclosed by the customer, to access STS tokens by using the metadata service, security risks may arise. To prevent security risks and implement the principle of least privilege (PoLP), we recommend that you use the RAM Roles for Service Account feature. This feature improves the security of cloud resources and allows untrusted applications to obtain STS tokens in a secure manner. In this case, the ACK cluster creates a service account OpenID Connect (OIDC) token file, associates the token file with a pod, and then injects relevant environment variables into the pod. Then, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token of the RAM role. For more information about the RRSA feature, see Use RRSA to authorize different pods to access different cloud services. The following environment variables are injected into the pod:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

package main

import (
	"os"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)

func main() {

    config := sdk.NewConfig()

    // Use the RAM role of the OIDC identity provider (IdP) to initialize an SDK client.
    credential, err := credentials.NewOIDCCredentialsProviderBuilder().
	// Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
	WithOIDCProviderARN(os.Getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN")).
	// Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
	WithOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
	// "<Role_Arn>" Required. The ARN of the RAM role. You can obtain the ARN of a RAM role in the RAM console. Example: acs:ram::123456789012****:role/adminrole.
	WithRoleArn("<Role_Arn>").
	// "<ROLE_SESSION_NAME>" Required. Specify a name for the role session. Example: alice. 
	WithRoleSessionName("<ROLE_SESSION_NAME>").
	// "<POLICY>": Optional. Grant limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}. 
	WithPolicy("<POLICY>").
	// <ROLE_SESSION_EXPIRATION>: Specify a validity period for the session. Example: 3600. 
	WithDurationSeconds(3600).
	Build()
     if err != nil {
	 panic(err)
    }   
    
    // <REGION_ID>: Specify the Alibaba Cloud region that the SDK client needs to access. Example: cn-hangzhou. 
    client, err := sdk.NewClientWithOptions("<REGION_ID>", config, credential)
    if err != nil {
	 panic(err)
    }
    
    // The step of calling an API operation is omitted.
}

Method 7: Use a bearer token

Only Cloud Call Center allows you to use a bearer token to initialize an SDK client.

package main

import (
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)

func main() {

    config := sdk.NewConfig()

    // <BEARER_TOKEN> specifies a type of authentication method for API calls.
    credential := credentials.NewBearerTokenCredentialsProvider("<BEARER_TOKEN>")
    
    // <REGION_ID>: Specify the Alibaba Cloud region that the SDK client needs to access. Example: cn-hangzhou. 
    client, err := sdk.NewClientWithOptions("<REGION_ID>", config, credential)
    if err != nil {
	panic(err)
    }
    
    // The step of calling an API operation is omitted.
}

Default credential provider chain

If you want to use different types of credentials in the development and production environments, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of the Credentials tool allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you use credentials.NewDefaultCredentialsProvider() to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order:

1. Obtain the credential information from environment variables

If no credentials are found in the previous step, the Credentials tool obtains the credential information from environment variables.

  • If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID) and ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret) system environment variables are specified, the Credentials tool uses the specified AccessKey pair as the default credential.

  • If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID), ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret), and ALIBABA_CLOUD_SECURITY_TOKEN (STS token) system environment variables are specified, the Credentials tool uses the specified STS token as the default credential.

2. Obtain the credential information by using the RAM role of an OIDC IdP

If no credentials are found in the previous step, the Credentials tool obtains the values of the following environment variables:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

If the preceding three environment variables are specified, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token as the default credential.

3. Obtain the credential information from the config.json file

If no credentials are found in the previous step, the Credentials tool obtains the credential information from the config.json file. The path of the configuration file varies based on the operating system:

Linux: ~/.aliyun/config.json

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

If the config.json file exists, the application initializes a Credentials client by using credential information that is specified by the current parameter in the config.json file. You can also specify the ALIBABA_CLOUD_PROFILE environment variable to specify the credential information. For example, you can set the ALIBABA_CLOUD_PROFILE environment variable to client1.

The mode parameter in the config.json file specifies the method that is used to obtain the credential information. Valid values:

  • AK: uses the AccessKey pair of a RAM user to obtain the credential information.

  • RamRoleArn: uses the ARN of a RAM role to obtain the credential information.

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

  • OIDC: uses the ARN of an OIDC IdP and the OIDC token file to obtain the credential information.

  • ChainableRamRoleArn: uses a role chain and specifies an access credential in another JSON file to obtain the credential information.

Configuration example:

{
	"current": "default",
	"profiles": [
		{
			"name": "default",
			"mode": "AK",
			"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
			"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
		},
		{
			"name":"client1",
			"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":"client2",
			"mode":"EcsRamRole",
			"ram_role_name":"<RAM_ROLE_ARN>"
		},
		{
			"name":"client3",
			"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":"client4",
			"mode":"ChainableRamRoleArn",
			"source_profile":"<PROFILE_NAME>",
			"ram_role_arn":"<ROLE_ARN>",
			"ram_session_name":"<ROLE_SESSION_NAME>",
			"expired_seconds":3600
		}
	]
}

4. Obtain the credential information from the RAM role of the ECS instance

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_ECS_METADATA environment variable that specifies the RAM role name of an ECS instance. If the RAM role exists, the application obtains an STS token of the RAM role as the default credential by using the metadata server of ECS in security hardening mode (IMDSv2). If an exception occurs in the security hardening mode (IMDSv2), the Credentials tool obtains the access credential in normal mode. You can also configure the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to specify an exception handling logic. Valid values of the environment variable:

  1. false (default): The Credentials tool continues to obtain the access credential in normal mode.

  2. true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode.

The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2).

5. Use a credential URI

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_CREDENTIALS_URI environment variable that specifies the URI of the credential. If the URI of the credential exists, the application uses the URI of the credential to obtain an STS token as the default credential.

References