All Products
Search
Document Center

Alibaba Cloud SDK:Initialize an SDK client and send API requests

Last Updated:Oct 22, 2024

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 SDK V1.0 for Go. The access credential ensures the access security when you use the SDK for development.

Initialize an SDK client

  • 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"
    )
    
    func main() {
    	// Use an AccessKey pair to initialize an SDK client.
            // In this example, the AccessKey pair of a RAM user is obtained from environment variables. This prevents security risks caused by hard coding.
    	client, err := sdk.NewClientWithAccessKey("<regionId>", os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
    }
    
  • 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"
    )
    
    func main() {
    	// Use an STS token to initialize an SDK client.
    	// This method is suitable for scenarios that require temporary access permissions, such as granting temporary access permissions to elastic container instances (ECIs).
    	client, err := sdk.NewClientWithStsToken("<regionId>", os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), os.Getenv("ALIBABA_CLOUD_SECURITY_TOKEN"))
    }
  • Use a RAM role

    You can specify the Alibaba Cloud Resource Name (ARN) of a RAM role to initialize an SDK client. The underlying logic of this method is to obtain an STS token by calling the STS API before sending API requests.

    package main
    
    import (
        "os"
    
        "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    )
    
    func main() {
        // Specify the ARN of a RAM role to initialize an SDK client.
        // "<regionId>": Specify the ID of the Alibaba Cloud region that the SDK client accesses.
        // os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"): Obtain the AccessKey ID of the RAM user from an environment variable.
        // os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"): Obtain the AccessKey secret of the RAM user from an environment variable.
        // "<roleArn>": Specify the ARN of the RAM role to be assumed.
        // "<roleSessionName>": Specify the name of the role session, which is used to identify and distinguish different sessions.
        client, err := sdk.NewClientWithRamRoleArn("<regionId>", os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "<roleArn>", "<roleSessionName>")
    }
    
  • Use a RAM role with custom permissions

    If you want to restrict the permissions of the STS token used to initialize an SDK client, you can specify a custom policy.

    package main
    
    import (
    	"os"
    
    	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    )
    
    func main() {
    	// Specify the ARN of a RAM role and a custom policy to initialize an SDK client.
    	// "<regionId>": Specify the ID of the Alibaba Cloud region that the SDK client accesses.
    	// os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"): Obtain the AccessKey ID of the RAM user from an environment variable.
    	// os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"): Obtain the AccessKey secret of the RAM user from an environment variable.
    	// "<roleArn>": Specify the ARN of the RAM role to be assumed.
    	// "<roleSessionName>": Specify the name of the role session, which is used to identify and distinguish different sessions.
    	// "<policy>": Specify a custom policy to restrict the role session permissions.
    	client, err := sdk.NewClientWithRamRoleArnAndPolicy("<regionId>", os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    		os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "<roleArn>", "<roleSessionName>", "<policy>")
    }
  • Use the RAM role of an ECS instance

    A client can use the metadata server of Elastic Compute Service (ECS) to obtain an STS token by using the RAM role attached to an ECS instance. The STS token is then used to initialize the client.

    package main
    
    import (
    	"os"
    
    	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    )
    
    func main() {
        // 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.
        // Replace "<regionId>" with the ID of the Alibaba Cloud region that the SDK client accesses and "<roleName>" with the name of the RAM role to be used.
        client, err := sdk.NewClientWithEcsRamRole("<regionId>", "<roleName>")
    }
    
  • Use the RAM role of an OIDC IdP

    After you attach a RAM role to a worker node in a Container Service for Kubernetes (ACK) cluster, you can use the RAM Roles for Service Accounts (RRSA) feature to allow different applications in an ACK cluster to assume different RAM roles. Applications can assume specific RAM roles, obtain STS tokens, and then use the tokens to access cloud services. This enforces the principle of least privilege and allows applications to call API operations without the need to use AccessKey pairs, which prevents AccessKey pair leaks.

    ACK 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. The Credentials tool uses the environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain an STS token of the RAM role. For more information, see Use RRSA to authorize different pods to access different cloud services.

    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.
    	oidcProvider, _ := 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")).
    		// Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
    		WithRoleArn(os.Getenv("ALIBABA_CLOUD_ROLE_ARN")).
    		// Specify the role session name.
    		WithRoleSessionName("<RoleSessionName>").
    		// Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    		WithPolicy("<Policy>").
    		// Specify the validity period of the session.
    		WithDurationSeconds(3600).
    		Build()
    
    	client, err := sdk.NewClientWithOptions("cn-beijing", config, oidcProvider)
    }
    
  • 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"
    )
    
    func main() {
        // Use a bearer token to initialize an SDK client.
        // Replace "<regionId>" with the region ID of the Alibaba Cloud region that you want to access a service. Bearer tokens are used for authentication of API calls.
        client, err := sdk.NewClientWithBearerToken("<regionId>", "<bearerToken>")
    }
  • Use the default credential provider chain

    If you do not specify a method to initialize a client, the default credential provider chain is used. You can also customize the credential provider chain. You can use a custom credential provider chain to obtain credentials, or write a closure to pass the provider.

    package main
    
    import (
        "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
        "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
    )
    
    func main() {
        ProviderEnv := provider.NewEnvProvider()
        ProviderProfile := provider.NewProfileProvider()
        ProviderInstance := provider.NewInstanceCredentialsProvider()
    
        // You can use a custom credential provider chain to obtain credentials. Credentials are used in the following order by default: ProviderEnv, ProviderProfile, and ProviderInstance.
        client, err := sdk.NewClientWithProvider("<regionId>", ProviderInstance, ProviderProfile, ProviderEnv)
    }

    The default credential provider chain searches for and uses credentials in the following order:

    The credential provider chain first searches for credentials in the environment variables. If the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are defined and specified, the specified AccessKey pair is used to create a default client. If the client that is specified in a request is not the default client, the credential provider chain searches for and loads a client in the configuration file.

    If a default file exists in the home directory of the user, the provider chain automatically creates a client based on the specified type and name. The path for the default file is ~/.alibabacloud/credentials. In Windows, the path is C:\Users\USER_NAME\.alibabacloud\credentials. If the default credential file exists but the system fails to parse the file, an exception is thrown. The client name is not case-sensitive. If two clients have the same name, the most recent client overwrites the client that is created earlier. You can also load a specific file by running AlibabaCloud::load('/data/credentials', 'vfs://AlibabaCloud/credentials', ...);. Different projects or tools can share this configuration file because the file is stored outside the projects and cannot be accidentally committed to version control. In Windows, you can use the environment variable %UserProfile% to reference your home directory. In Unix-like systems, you can use the environment variable $HOME or a tilde (~) to reference your home directory. You can modify the path of the default file when you define the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable.

    [default]                          # The default client.
    type = access_key                  # The authentication is based on AccessKey pairs.
    access_key_id = foo                # Key
    access_key_secret = bar            # Secret
    
    [client1]                          # The client named client1.
    type = ecs_ram_role                # The authentication is based on EcsRamRole credentials.
    role_name = EcsRamRoleTest         # Role Name
    
    [client2]                          # The client named client2.
    type = ram_role_arn                # The authentication is based on RamRoleArn credentials.
    access_key_id = foo
    access_key_secret = bar
    role_arn = role_arn
    role_session_name = session_name

    If you define the environment variable ALIBABA_CLOUD_ECS_METADATA and the environment variable is not empty, the credential provider chain uses the value of the environment variable as the role name, sends a request to http://100.100.100.200/latest/meta-data/ram/security-credentials/ to obtain temporary security credentials, and then creates a default client.

  • Specify runtime parameters

    You can specify runtime parameters when you initialize an SDK client. Supported settings include proxy, timeout period, retry mechanism, and asynchronous calls.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
    )
    
    func main() {
    	// Specify runtime parameters.
    	config := sdk.NewConfig()
    	// Use the AccessKey ID and AccessKey secret of the RAM user.
    	credential := credentials.NewAccessKeyCredential(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
    	client, err := sdk.NewClientWithOptions("<regionId>", config, credential)
    	if err != nil {
    		panic(err)
    	}

Send API requests

Use CommonRequest to send API requests

You need to only use the core package to send API requests. You do not need to install service SDKs. To send an API request, use a CommonRequest object to construct request parameters and then invoke the ProcessCommonRequest function. For more information, see Use CommonRequest.

Use Alibaba Cloud SDKs to make specialized calls

To make specialized calls, you must install SDKs of Alibaba Cloud services. To install SDKs of Alibaba Cloud services, perform the following steps:

  1. Go to the SDK Center.

  2. In the top navigation bar, move the pointer over Cloud Products and choose Computing > Elastic Compute Service.

  3. On the page that appears, select an API version. If multiple versions are available, select the recommended or latest version.

  4. Set the SDK Generation parameter to V1.0.

  5. Select Go in the All languages section.

  6. Copy the command from the Installation Method section, paste the command to the terminal, and then run the command.

go get github.com/aliyun/alibaba-cloud-sdk-go/services/ecs

Example

package main

import (
	"fmt"

	"os"

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

func main() {
	// Specify runtime parameters.
	config := sdk.NewConfig()
	// Use the AccessKey ID and AccessKey secret of the RAM user.
	credential := credentials.NewAccessKeyCredential(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
	client, err := ecs.NewClientWithOptions("cn-hangzhou", config, credential)
	if err != nil {
		panic(err)
	}
	// Use the request object provided by the cloud service SDK.
	request := ecs.CreateDescribeRegionsRequest()
	request.Scheme = "https" // The request protocol.
	// Specify the request parameters.
	request.InstanceChargeType = "PrePaid" // The billing method of the instance.
	request.ResourceType = "instance" // The resource type.
	// Send the request and obtain a response.
	response, err := client.DescribeRegions(request)
	if err != nil {
		fmt.Print(err.Error())
	}
	fmt.Printf("response is %#v\n", response)
}