All Products
Search
Document Center

Elastic Compute Service:Example on how to use ECS SDK V2.0 for Go

Last Updated:Oct 21, 2024

This topic describes how to install Elastic Compute Service (ECS) SDK V2.0 for Go and provides an example on how to use the SDK to call ECS API operations. In the example, ECS SDK V2.0 for Go is used to call the DescribeInstances operation to query information about ECS instances.

Prerequisites

  1. A Resource Access Management (RAM) user with the minimum required permissions is logged on using its AccessKey pair. We do not recommend that you use Alibaba Cloud account because it has full permissions and its AccessKey pair is a significant security risk if compromised. For more information about creating an AccessKey pair, see Create an AccessKey pair.

  2. The RAM user is authorized to manage ECS resources. This example requires read-only access, and the AliyunECSReadonlyAccess system policy is used. Authorize permissions according to your business requirements.

    1. Create a custom policy.

      For guidance on creating a custom policy, see Create custom policies and RAM authorization.

      ECS offers custom policy templates based on best practices. Refer to those policy templates to quickly establish policies based on your needs. For more information, see Custom policies for ECS.

    2. Use system policies.

      For more information about ECS-supported system policies and their permissions, see System policies for ECS.

  3. An AccessKey pair is configured in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.

Install ECS SDK V2.0 for Go

For information about how to install ECS SDK V2.0 for Go, visit the SDK Center. You can copy the following command and run the command in the terminal to install ECS SDK V2.0 for Go:

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

Use ECS SDK V2.0 for Go

1. Initialize a client.

Alibaba Cloud SDKs support multiple access credentials, such as AccessKey pairs and Security Token Service (STS) tokens, to initialize clients. For more information, see Manage access credentials. In this example, an AccessKey pair is used to initialize a client.

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 configured. 
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// Specify an endpoint. For information about endpoints, visit 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 a request object, view the parameters of the API operation that you want to call. In this example, the DescribeInstances operation is used. You can view the parameters of the DescribeInstances operation in DescribeInstances.

Note

The name of a request object is in the {Operation name}Request format. For example, the request object for the DescribeInstances operation is named DescribeInstancesRequest.

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

3. Call the API operation.

When you call an API operation from a client, you can specify runtime parameters, such as timeout parameters and proxy parameters. For more information, see Advanced configuration.

Note

The name of a response object is in the {Operation name}Response format. For example, the response object for the DescribeInstances operation is named DescribeInstancesResponse.

// Specify 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.

ECS SDK for Go classifies exceptions into the following types:

  • error: This type of exception is caused by non-business errors. For example, an error exception is thrown if the verification fails because the SDK source file is modified or if the parsing fails.

  • SDKError: In most cases, this type of exception is caused by business errors.

We recommend that you properly handle exceptions by performing operations, such as reporting exceptions, logging exceptions, and performing retries, to ensure the robustness and stability of your system.

5. Complete sample code.

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 configured. 
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// Specify an endpoint. For information about endpoints, visit 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"),
	}
	// Specify 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 { // Check whether the tryErr error is of the *tea.SDKError type based on the type assertion.
			// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided only for reference. 
			fmt.Println(tea.StringValue(sdkError.Message))
			fmt.Println(tea.StringValue(sdkError.Code))
			fmt.Println(tea.StringValue(sdkError.Data))
		} else {
			// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided only for reference. 
			fmt.Println(tea.String(tryErr.Error()))
		}
	} else {
		fmt.Println(resp.Body)
	}
}

References

You can also use ECS SDK V2.0 for Go to perform generic calls to ECS API operations. For more information, see Generic calls.

If you use ECS SDK V1.0 for Go, see V1.0 Go SDK for information about the SDK.