How to Create an EC2 Instance with AWS SDK

Postgraduate in Communications Engineering with working experience in the Support Desk and self-study in software development.
Search for a command to run...

Postgraduate in Communications Engineering with working experience in the Support Desk and self-study in software development.
The git log command is used to view the commit history of a Git repository. You can customize the output format to show specific details in a more readable or structured way. Below are some useful variations and formatting options for git log: To sh...

Overview This article will teach us how to: Install Ubuntu Server 24.04 on a laptop from scratch Install Ubuntu server by using Vagrant tool with ISO image Prerequisites: A laptop without any OS installed; A virtualization software Virtualbox t...

The /etc/passwd and /etc/shadow files are the backbone of Linux user management. Together, they store user account information and handle authentication securely. This article provides a hands-on guide to understanding these files, their structure, a...

In Linux, links are powerful tools that allow you to create references to files and directories. There are two main types of links: hard links and soft links (also known as symbolic links or symlinks). Understanding the differences between these two ...

A hostname is a human-friendly name given to a computer. It is a unique identifier that allows us to identify the machine in various network communications, making it easier to locate and manage devices. Type: hostname To see where it is stored, typ...

What is AWS SDK?
Prerequisites
Create EC2 instance with AWS SDK
References
The AWS SDK (Amazon Web Services Software Development Kit) is a collection of libraries and tools that developers use to interact with and access various Amazon Web Services (AWS) cloud services.
The AWS SDK abstracts the complexities of handling AWS APIs and authentication, making it easier for developers to interact with AWS services programmatically and build scalable, flexible, and robust applications on top of AWS infrastructure.
Installed AWS CLI;
Configured AWS CLI with aws configure command;
Initialize a new npm project with the command:
npm init -y
Install an aws-sdk package locally with the command:
npm install aws-sdk
Create a createInstance.js file inside the project:
touch createInstance.js
First, import the AWS SDK (Software Development Kit) library into your code in the file createInstance.js:
const AWS = require("aws-sdk");
We can then use AWS variable to access various AWS services, create instances, make API calls, and manage AWS resources using the methods provided by the SDK.
Then, update the AWS SDK configuration with the following credentials and the region:
AWS.config.update({
"accessKeyId": "xxx",
"secretAccessKey": "xxx",
"region": "us-east-1"
})
The SDK will use this information when making requests to AWS services. This ensures that your requests are properly authenticated and directed to the correct region, allowing you to work with AWS services securely and efficiently.
Next, create an instance of the AWS EC2 service object with a specified API version:
const ec2 = new AWS.EC2({apiVersion: "2016-11-15"});
Using a specific API version ensures that your code remains consistent and doesn't break unexpectedly when AWS introduces changes to its service APIs. It also allows you to use new features and improvements available in a specific API version. Now, we can use ec2 object's methods to perform various operations related to Amazon EC2.
Create a JS object named instanceParams that contain parameters to be used for creating a new Amazon EC2 instance using the AWS SDK.
const instanceParams = {
ImageId: "ami-053b0d53c279acc90",
InstanceType: "t2.micro",
KeyName: "demo-key",
MinCount: 1,
MaxCount: 1
}
Using promises in JavaScript, create an EC2 instance with the AWS SDK:
const instancePromise = ec2.runInstances(instanceParams).promise()
// Handle promise's fulfilled and rejected states
instancePromise.then(function(data){
console.log(data);
const instanceId = data.Instances[0].InstanceId;
console.log("Created instance: ", instanceId);
}).catch(function(err){
console.log(err, err.stack);
})
The code above sets up a promise chain to create an EC2 instance using the runInstances() method, handle the response data to extract the instance ID and log the instance ID if the creation is successful. If any errors occur during the process, the code logs the error message and stack trace to the console.
Finally, run the code with the command:
node createInstance.js
The output is:

Check whether the instance is running via AWS Console:
