All Products
Search
Document Center

Elastic Compute Service:Use ECS SDK V2.0 for Go

Last Updated:Jan 30, 2026

This topic describes how to install and use the Go V2.0 software development kit (SDK). An example is provided on how to use the DescribeInstances API operation to query the details of one or more Elastic Compute Service (ECS) instances.

Prerequisites

  1. The AccessKey of an Alibaba Cloud account provides full access to your resources, which poses a high security risk if the AccessKey is leaked. We recommend that you create a Resource Access Management (RAM) user and grant the RAM user only the required permissions. Then, use the AccessKey of the RAM user to call API operations. For more information, see Create an AccessKey.

  2. You have granted the RAM user permissions to manage ECS resources. The example code in this topic shows a query operation. In this example, the AliyunECSReadonlyAccess system policy is used. You can grant custom permissions as needed.

    1. Use custom policies.

      For more information about how to create custom policies, see Create a custom policy and Authorization information.

      ECS provides custom policy examples based on best practices. You can use these examples to quickly create custom policies that meet your business needs. For more information, see Custom policies.

    2. Use system policies.

      For information about all system policies that ECS supports and their permission descriptions, see System policies for ECS.

  3. Configure the AccessKey using environment variables. For more information, see Configure environment variables on Linux, macOS, and Windows systems.

Install the SDK

For information about how to install the Go V2.0 SDK, see SDK Center. Copy the following command and run it in your terminal to install the ECS SDK:

// Initialize the Go module if your project does not have a go.mod file.
go mod init <PROJECT_NAME>

go get -u github.com/alibabacloud-go/darabonba-openapi/v2/client

Use the SDK

1. Initialize the client

The Alibaba Cloud SDK supports multiple types of access credentials to initialize a client, such as an AccessKey and a Security Token Service (STS) token. For more information, see Manage access credentials. This example shows how to initialize a client using an AccessKey.

package main

import (
	"os"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
	"github.com/alibabacloud-go/tea/tea"
)

func CreateClient() (_result *ecs20140526.Client, _err error) {
	config := &openapi.Config{
		// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// For the Endpoint, see https://api.aliyun.com/product/Ecs
	config.Endpoint = tea.String("ecs.cn-hangzhou.aliyuncs.com")
	_result = &ecs20140526.Client{}
	_result, _err = ecs20140526.NewClient(config)
	return _result, _err
}

2. Create a request object for the API operation

Before you create the request object, view the API documentation for the operation to obtain parameter information.

Note

The naming convention for a request object is {APIName}Request. For example, the request object for the DescribeInstances operation is DescribeInstancesRequest.

// Create a request object.
describeInstancesRequest := &ecs20140526.DescribeInstancesRequest{
    RegionId: tea.String("cn-hangzhou"),
  }

3. Initiate a call

When you use a client to call an OpenAPI operation, you can set runtime parameters, such as timeout and proxy configurations. For more information, see Advanced configurations.

Note

The naming convention for a response object is {APIName}Response. For example, the response object for the DescribeInstances operation is DescribeInstancesResponse.

// Set runtime parameters.
runtime := &util.RuntimeOptions{}
// Call the DescribeInstances operation.
response, _err := ecsClient.DescribeInstancesWithOptions(describeInstancesRequest, runtime)
if _err != nil {
	panic(_err)
}
fmt.Println(response.Body.String())

4. Handle exceptions

The Go SDK classifies exceptions into the following main error types:

  • error: A generic error that is not specific to the API operation, such as a validation error caused by a modified SDK source file or a parsing error.

  • SDKError: A business error that occurs during an SDK request.

Take appropriate measures to handle exceptions, such as propagating exceptions, recording logs, and attempting to recover. This helps ensure the robustness and stability of your system.

5. Complete example

package main

import (
	"fmt"
	"os"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func CreateClient() (_result *ecs20140526.Client, _err error) {
	config := &openapi.Config{
		// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// For the Endpoint, see https://api.aliyun.com/product/Ecs
	config.Endpoint = tea.String("ecs.cn-hangzhou.aliyuncs.com")
	_result = &ecs20140526.Client{}
	_result, _err = ecs20140526.NewClient(config)
	return _result, _err
}

func main() {
	ecsClient, _err := CreateClient()
	if _err != nil {
		panic(_err)
	}
	// Create a request object.
	describeInstancesRequest := &ecs20140526.DescribeInstancesRequest{
		RegionId: tea.String("cn-hangzhou"),
	}
	// Set runtime parameters.
	runtime := &util.RuntimeOptions{}
	resp, tryErr := func() (response *ecs20140526.DescribeInstancesResponse, _e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// Call the DescribeInstances operation.
		response, _err := ecsClient.DescribeInstancesWithOptions(describeInstancesRequest, runtime)
		if _err != nil {
			return nil, _err
		}
		return response, nil
	}()

	if tryErr != nil {
		if sdkError, ok := tryErr.(*tea.SDKError); ok { // Use a type assertion to check if tryErr is of the *tea.SDKError type.
			// This is for printing purposes only. Handle exceptions with care. Do not ignore exceptions in your projects.
			fmt.Println(tea.StringValue(sdkError.Message))
			fmt.Println(tea.StringValue(sdkError.Code))
			fmt.Println(tea.StringValue(sdkError.Data))
		} else {
			// This is for printing purposes only. Handle exceptions with care. Do not ignore exceptions in your projects.
			fmt.Println(tea.String(tryErr.Error()))
		}
	} else {
		fmt.Println(resp.Body)
	}
}

Scenario-based examples

More information

In addition to the preceding method, you can use generalized calls to invoke ECS OpenAPI operations. For more information, see Generalized calls.

If you are using the V1.0 SDK and want to learn more about it, see V1.0 Go SDK.