What is @aws-sdk/client-ec2?
@aws-sdk/client-ec2 is a part of the AWS SDK for JavaScript, which allows developers to interact with Amazon EC2 (Elastic Compute Cloud) services. This package provides a comprehensive set of functionalities to manage EC2 instances, security groups, key pairs, and other related resources programmatically.
What are @aws-sdk/client-ec2's main functionalities?
Launch an EC2 Instance
This code sample demonstrates how to launch a new EC2 instance using the @aws-sdk/client-ec2 package. It specifies the AMI ID, instance type, and the number of instances to launch.
const { EC2Client, RunInstancesCommand } = require('@aws-sdk/client-ec2');
const client = new EC2Client({ region: 'us-west-2' });
const run = async () => {
const command = new RunInstancesCommand({
ImageId: 'ami-0abcdef1234567890',
InstanceType: 't2.micro',
MinCount: 1,
MaxCount: 1
});
const response = await client.send(command);
console.log(response);
};
run();
Describe EC2 Instances
This code sample shows how to describe EC2 instances using the @aws-sdk/client-ec2 package. It retrieves information about all EC2 instances in the specified region.
const { EC2Client, DescribeInstancesCommand } = require('@aws-sdk/client-ec2');
const client = new EC2Client({ region: 'us-west-2' });
const describe = async () => {
const command = new DescribeInstancesCommand({});
const response = await client.send(command);
console.log(response);
};
describe();
Terminate an EC2 Instance
This code sample demonstrates how to terminate an EC2 instance using the @aws-sdk/client-ec2 package. It specifies the instance ID of the EC2 instance to be terminated.
const { EC2Client, TerminateInstancesCommand } = require('@aws-sdk/client-ec2');
const client = new EC2Client({ region: 'us-west-2' });
const terminate = async () => {
const command = new TerminateInstancesCommand({
InstanceIds: ['i-0abcdef1234567890']
});
const response = await client.send(command);
console.log(response);
};
terminate();
Create a Security Group
This code sample shows how to create a new security group using the @aws-sdk/client-ec2 package. It specifies the group name, description, and VPC ID.
const { EC2Client, CreateSecurityGroupCommand } = require('@aws-sdk/client-ec2');
const client = new EC2Client({ region: 'us-west-2' });
const createSecurityGroup = async () => {
const command = new CreateSecurityGroupCommand({
GroupName: 'my-security-group',
Description: 'My security group',
VpcId: 'vpc-0abcdef1234567890'
});
const response = await client.send(command);
console.log(response);
};
createSecurityGroup();
Other packages similar to @aws-sdk/client-ec2
aws-sdk
The 'aws-sdk' package is the older version of the AWS SDK for JavaScript. It provides a wide range of AWS services, including EC2. However, it is not modular like the v3 SDK, which means you have to install the entire SDK even if you only need EC2 functionalities.
aws-cdk
The 'aws-cdk' (AWS Cloud Development Kit) allows developers to define cloud infrastructure using code. It supports multiple programming languages and provides higher-level abstractions for AWS services, including EC2. It is more suitable for infrastructure as code (IaC) use cases compared to the @aws-sdk/client-ec2 package.
serverless
The 'serverless' framework is used to build and deploy serverless applications on AWS and other cloud providers. It supports AWS Lambda, API Gateway, and other services, including EC2. It provides a higher-level abstraction and is more focused on serverless architectures compared to the @aws-sdk/client-ec2 package.
@aws-sdk/client-ec2

Description
AWS SDK for JavaScript EC2 Client for Node.js, Browser and React Native.
Amazon Elastic Compute Cloud
Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing capacity in the AWS cloud.
Using Amazon EC2 eliminates the need to invest in hardware up front, so you can develop and
deploy applications faster.
To learn more, see the following resources:
Installing
To install the this package, simply type add or install @aws-sdk/client-ec2
using your favorite package manager:
npm install @aws-sdk/client-ec2
yarn add @aws-sdk/client-ec2
pnpm add @aws-sdk/client-ec2
Getting Started
Import
The AWS SDK is modulized by clients and commands.
To send a request, you only need to import the EC2Client
and
the commands you need, for example AcceptReservedInstancesExchangeQuoteCommand
:
const { EC2Client, AcceptReservedInstancesExchangeQuoteCommand } = require("@aws-sdk/client-ec2");
import { EC2Client, AcceptReservedInstancesExchangeQuoteCommand } from "@aws-sdk/client-ec2";
Usage
To send a request, you:
- Initiate client with configuration (e.g. credentials, region).
- Initiate command with input parameters.
- Call
send
operation on client with command object as input. - If you are using a custom http handler, you may call
destroy()
to close open connections.
const client = new EC2Client({ region: "REGION" });
const params = {
};
const command = new AcceptReservedInstancesExchangeQuoteCommand(params);
Async/await
We recommend using await
operator to wait for the promise returned by send operation as follows:
try {
const data = await client.send(command);
} catch (error) {
} finally {
}
Async-await is clean, concise, intuitive, easy to debug and has better error handling
as compared to using Promise chains or callbacks.
Promises
You can also use Promise chaining
to execute send operation.
client.send(command).then(
(data) => {
},
(error) => {
}
);
Promises can also be called using .catch()
and .finally()
as follows:
client
.send(command)
.then((data) => {
})
.catch((error) => {
})
.finally(() => {
});
Callbacks
We do not recommend using callbacks because of callback hell,
but they are supported by the send operation.
client.send(command, (err, data) => {
});
v2 compatible style
The client can also send requests using v2 compatible style.
However, it results in a bigger bundle size and may be dropped in next major version. More details in the blog post
on modular packages in AWS SDK for JavaScript
import * as AWS from "@aws-sdk/client-ec2";
const client = new AWS.EC2({ region: "REGION" });
try {
const data = client.acceptReservedInstancesExchangeQuote(params);
} catch (error) {
}
client
.acceptReservedInstancesExchangeQuote(params)
.then((data) => {
})
.catch((error) => {
});
client.acceptReservedInstancesExchangeQuote(params, (err, data) => {
});
Troubleshooting
When the service returns an exception, the error will include the exception information,
as well as response metadata (e.g. request id).
try {
const data = await client.send(command);
} catch (error) {
const { requestId, cfId, extendedRequestId } = error.$metadata;
console.log({ requestId, cfId, extendedRequestId });
}
Getting Help
Please use these community resources for getting help.
We use the GitHub issues for tracking bugs and feature requests, but have limited bandwidth to address them.
To test your universal JavaScript code in Node.js, browser and react-native environments,
visit our code samples repo.
Contributing
This client code is generated automatically. Any modifications will be overwritten the next time the @aws-sdk/client-ec2
package is updated.
To contribute to client you can check our generate clients scripts.
License
This SDK is distributed under the
Apache License, Version 2.0,
see LICENSE for more information.