This topic describes how to install Elastic Compute Service (ECS) SDK V2.0 for Node.js and provides an example on how to use the SDK to call ECS API operations. In the example, ECS SDK V2.0 for Node.js is used to call the DescribeInstances operation to query information about ECS instances.
Prerequisites
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.
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.
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.
Use system policies.
For more information about ECS-supported system policies and their permissions, see System policies for ECS.
An AccessKey pair is configured in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.
Install SDK
For instructions on installing the SDK V2.0 for Node.js, visit the SDK Center. Run the following command in the terminal to install the ECS SDK:
npm install --save @alicloud/ecs20140526@4.3.0
Use SDK
1. Initialize client
Alibaba Cloud SDKs support various access credentials, such as AccessKey pairs and Security Token Service (STS) tokens, to initialize clients. For more information, see Manage access credentials. The following examples initialize the client using an AccessKey pair.
TypeScript example
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
export class Client {
static createClient() {
let config = new $OpenApi.Config({
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in the runtime environment.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in the runtime environment.
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint: `ecs-cn-hangzhou.aliyuncs.com`,
});
return new Ecs20140526(config);
}
}
JavaScript example
const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
class Client {
static createClient() {
const config = new OpenApi.Config({
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in the runtime environment.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in the runtime environment.
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint: `ecs-cn-hangzhou.aliyuncs.com`,
});
return new Ecs20140526.default(config);
}
}
2. Construct a request object
Before you construct a request object, see DescribeInstances for parameter details.
The name of a request object must be in the {API name}Request
format. For example, the request object for DescribeInstances
is DescribeInstancesRequest
.
TypeScript example
// Construct the request object.
const describeInstancesRequest = new Ecs20140526.DescribeInstancesRequest({
regionId: "cn-hangzhou",
});
JavaScript example
// Construct the request object.
const describeInstancesRequest = new Ecs20140526.DescribeInstancesRequest({
regionId: "cn-hangzhou",
});
3. Initiate a call
When you call API operations through the client, you can configure runtime parameters such as timeout and proxy settings. For more information, see Advanced configuration.
The name of a response object must be in the {API name}Response
format. For example, the response object for DescribeInstances
is DescribeInstancesResponse
.
TypeScript example
// Create the runtime configuration object.
const runtime = new $Util.RuntimeOptions();
// Initiate the request.
const describeInstancesResponse = await client.describeInstancesWithOptions(describeInstancesRequest, runtime);
JavaScript example
// Create the runtime configuration object.
const runtime = new Util.RuntimeOptions();
// Initiate the request.
const describeInstancesResponse = await client.describeInstancesWithOptions(describeInstancesRequest, runtime);
4. Handle Exceptions
The SDK for Node.js uses Promise
and async/await
for asynchronous operations and provides an error handling mechanism to catch and manage exceptions during API calls. When an API call fails, Alibaba Cloud SDKs throw an Error object. The SDK for Node.js categorizes exceptions into UnretryableError and ResponseError.
UnretryableError: This type of exception is caused by network issues. When the maximum number of retry attempts is reached, UnretryableError is thrown.
ResponseError: This type of exception is caused by business errors.
We recommend that you properly handle exceptions by performing operations such as reporting exceptions, recording logs, and performing retries. This helps ensure the robustness and stability of your system.
5. Sample code
TypeScript example
import * as $Util from '@alicloud/tea-util';
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import * as $OpenApi from '@alicloud/openapi-client';
export class Client {
static createClient() {
let config = new $OpenApi.Config({
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in the runtime environment.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in the runtime environment.
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint: `ecs-cn-hangzhou.aliyuncs.com`,
});
return new Ecs20140526(config);
}
static async main(): Promise<void> {
const client = Client.createClient();
// Construct the request object.
const describeInstancesRequest = new $Ecs20140526.DescribeInstancesRequest({
regionId: "cn-hangzhou",
});
// Create the runtime configuration object.
const runtime = new $Util.RuntimeOptions();
try {
// Initiate the request and capture the response.
const response = await client.describeInstancesWithOptions(describeInstancesRequest, runtime);
console.log('Describe Instances Response:', JSON.stringify(response.body));
} catch (error) {
// Handle exceptions with care in your project. Do not overlook them.
console.error('Error occurred:', error);
}
}
}
Client.main();
JavaScript example
const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
class Client {
static createClient() {
const config = new OpenApi.Config({
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in the runtime environment.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in the runtime environment.
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint: `ecs-cn-hangzhou.aliyuncs.com`,
});
return new Ecs20140526.default(config);
}
static async main() {
const client = Client.createClient();
// Construct the request object.
const describeInstancesRequest = new Ecs20140526.DescribeInstancesRequest({
regionId: "cn-hangzhou",
});
// Create the runtime configuration object.
const runtime = new Util.RuntimeOptions();
try {
// Initiate the request and capture the response.
const response = await client.describeInstancesWithOptions(describeInstancesRequest, runtime);
console.log('Describe Instances Response:', JSON.stringify(response.body));
} catch (error) {
// Handle exceptions with care in your project. Do not overlook them.
console.error('Error occurred:', error.message);
}
}
}
Client.main();
References
For alternative methods of calling ECS OpenAPI operations, refer to Generic calls.
For information about the SDK V1.0, see V1.0 Node.js SDK.