Amazon Elastic Compute Cloud (Amazon EC2) is an AWS service that launches instances on which we can host web pages and various other applications. Amazon EC2 provides scalable computing capacity in the Amazon Web Services (AWS) Cloud. The AWS SDK for JavaScript is a software development toolset allowing developers to interact with AWS services using JavaScript programming. It provides a convenient way to access and manage AWS services within a JavaScript environment.
For EC2, the JavaScript SDK allows developers to programmatically create, configure, and manage EC2 instances. Regarding the EC2 service, the AWS JavaScript SDK allows us to programmatically access EC2 instances and integrate EC2 resources with JavaScript-based web applications.
Let’s look at how to launch an EC2 instance using the AWS JavaScript SDK.
To progress with this Answer, we must have a working AWS account with the required EC2 permissions and our AWS access keys generated for that account.
To launch an EC2 instance, we’ll also first need to create a
The import statement to fetch the required AWS SDK commands for the required EC2 actions from the @aws-sdk/client-ec2
library is as follows:
const { EC2Client, RunInstancesCommand, CreateKeyPairCommand, DescribeSecurityGroupsCommand, DescribeInstancesCommand } = require('@aws-sdk/client-ec2');
The code snippet for creating an EC2 client that takes in the configuration setting and AWS credentials and uses them to connect with the EC2 service on the AWS Cloud is as follows:
const ec2Client = new EC2Client({region: 'us-east-1',credentials: {accessKeyId: 'AWS_ACCESS_KEY_ID',secretAccessKey: 'AWS_SECRET_ACCESS_KEY'}});
Here’s the code snippet for creating an EC2 key pair where we use the CreateKeyPairCommand
command to create a key pair.
const keyPairName = `edu-ans-keypair-${(Math.floor((Math.random()) * 99999999)+10000000)}`;const createKeyPairCommand = new CreateKeyPairCommand({ KeyName: keyPairName });const keyPairResult = await ec2Client.send(createKeyPairCommand);fs.writeFileSync(`${keyPairName}.pem`, keyPairResult.KeyMaterial);fs.chmodSync(`${keyPairName}.pem`, '400');
In the code above:
Line 1: We define the name of the key pair here and add a random number to the end of it.
Line 2: We define the createKeyPairCommand
command and configure it to use the key pair name we provided.
Line 3: We send the createKeyPairCommand
command to the AWS Cloud using the EC2 client and save the result in the keyPairResult
variable.
Line 4: We create a .pem
file with the key pair private key inside it. We’ll use this key pair later to connect with the EC2 instance.
Line 5: We change the file permissions of a .pem
file to 400
, which means that only the read permission is granted to the owner while all other permissions are denied. This is a required step by AWS for security reasons.
The code snippet for creating the security group with the appropriate inbound rules using the CreateSecurityGroupCommand
and AuthorizeSecurityGroupIngressCommand
command is as follows:
const createSecurityGroupCommand = new CreateSecurityGroupCommand({GroupName: `SecurityGroupName-${uniqueId}`, Description: 'This Security Group allows SSH connection on port 22'});const securityGroupsResult = await ec2Client.send(createSecurityGroupCommand);const authorizeSecurityGroupIngressCommand = new AuthorizeSecurityGroupIngressCommand({GroupId: securityGroupsResult.GroupId, IpPermissions: [{IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{CidrIp: '0.0.0.0/0'}]}]});await ec2Client.send(authorizeSecurityGroupIngressCommand);
In the code above:
Line 1: We define the createSecurityGroupCommand
command to create a security group with a unique name and appropriate description.
Line 2: We send the createSecurityGroupCommand
command to the AWS Cloud using the EC2 client and save the result in the securityGroupsResult
variable.
Lines 3-4: We define and execute the authorizeSecurityGroupIngressCommand
command that creates an inbound rule for the security group to open on port 22. This rule allows us to SSH into the EC2 instance.
The code snippet for launching an EC2 instance where we use the RunInstancesCommand
command with the appropriate configuration settings is as follows:
const runInstancesCommand = new RunInstancesCommand({ImageId: 'ami-0759f51a90924c166', // AMI ID for Amazon Linux 2023 in us-east-1InstanceType: 't2.micro',MinCount: 1,MaxCount: 1,KeyName: keyPairName, // Name of the key pairSecurityGroupIds: [defaultSecurityGroup.GroupId], // ID of the security group});const runInstancesResult = await ec2Client.send(runInstancesCommand);
In the code above:
Lines 1–8: We define the runInstancesCommand
command and provide the appropriate configuration settings for the EC2 instance.
Line 9: We send the runInstancesCommand
command to the AWS Cloud using the EC2 client and save the result in the runInstancesResult
variable.
The code snippet for fetching the details of the launched EC2 instance, where we use the DescribeInstancesCommand
command is as follows:
setTimeout(async () => {const describeInstancesCommand = new DescribeInstancesCommand({InstanceIds: [runInstancesResult.Instances[0].InstanceId]});const describeInstancesResult = await ec2Client.send(describeInstancesCommand);const publicIp = describeInstancesResult.Reservations[0].Instances[0].PublicDnsName;console.log(`ssh -i ${keyPairName}.pem ec2-user@${publicIp}`);}, 10000);
In the code above:
Lines 1–6: We set a timer for under ten seconds before fetching the details of the launched EC2 instance. This is important as it gives time for the EC2 instance to come into the “Running” state, after which a public DNS address is available for it.
Line 2: We define the describeInstancesCommand
command and configure it to fetch the EC2 instance we just launched using its ID.
Line 3: We send the describeInstancesCommand
command to the AWS Cloud using the EC2 client and save the result in the describeInstancesResult
variable.
Line 4: We extract the public DNS address of the EC2 instance from the runInstancesResult
variable.
Line 5: We output the appropriate SSH command to connect with the launch EC2 instance.
The following code executable will launch an EC2 instance, as well as create a key pair and a security group for it. Click the “Run” button to execute the script.
Make sure to add your AWS account’s access keys to the “aws_access_key_id” and “aws_secret_access_key” prompts.
// Import required libraries const { EC2Client, RunInstancesCommand, CreateKeyPairCommand, CreateSecurityGroupCommand, AuthorizeSecurityGroupIngressCommand, DescribeInstancesCommand } = require('@aws-sdk/client-ec2'); const fs = require('fs'); // Set your AWS credentials const credentials = { accessKeyId: process.env.access_key_id, secretAccessKey: process.env.secret_access_key }; // Set your AWS region const region = 'us-east-1'; // Create config object const config = { region: region, credentials: credentials } // Create an EC2 client const ec2Client = new EC2Client(config); // Function to launch an EC2 instance and create prerequisite resources async function launchEC2Instance() { try { const uniqueId = Math.floor((Math.random()) * 99999999)+10000000; // Create a key pair const keyPairName = `edu-ans-keypair-${uniqueId}`; const createKeyPairCommand = new CreateKeyPairCommand({ KeyName: keyPairName }); const keyPairResult = await ec2Client.send(createKeyPairCommand); fs.writeFileSync(`${keyPairName}.pem`, keyPairResult.KeyMaterial); fs.chmodSync(`${keyPairName}.pem`, '400'); // Create security group with appropriate inbound rules const createSecurityGroupCommand = new CreateSecurityGroupCommand({GroupName: `SecurityGroupName-${uniqueId}`, Description: 'This Security Group allows SSH connection on port 22'}); const securityGroupsResult = await ec2Client.send(createSecurityGroupCommand); const authorizeSecurityGroupIngressCommand = new AuthorizeSecurityGroupIngressCommand({GroupId: securityGroupsResult.GroupId, IpPermissions: [{IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{CidrIp: '0.0.0.0/0'}]}]}); await ec2Client.send(authorizeSecurityGroupIngressCommand); // Launch an EC2 instance const runInstancesCommand = new RunInstancesCommand({ // AMI ID for Amazon Linux 2023 ImageId: 'ami-0759f51a90924c166', InstanceType: 't2.micro', MinCount: 1, MaxCount: 1, // Name of the key pair KeyName: keyPairName, // ID of the security group SecurityGroupIds: [securityGroupsResult.GroupId], }); const runInstancesResult = await ec2Client.send(runInstancesCommand); // Fetch the EC2 instance’s IP address setTimeout(async () => { const describeInstancesCommand = new DescribeInstancesCommand({InstanceIds: [runInstancesResult.Instances[0].InstanceId]}); const describeInstanceResponse = await ec2Client.send(describeInstancesCommand); const publicIp = describeInstanceResponse.Reservations[0].Instances[0].PublicDnsName; console.log(`ssh -i ${keyPairName}.pem ec2-user@${publicIp}`); }, 10000); } catch (err) { console.error('Error launching EC2 instance:', err); } } // Call the function to launch the EC2 instance launchEC2Instance();
Upon the successful execution of the code above, the appropriate SSH command will be printed at the end of the terminal. We can use this command to SSH into the EC2 instance. The SSH command has the following format:
ssh -i edu-ans-keypair-<UNIQUE_ID>.pem ec2-user@<INSTANCE_PUBLIC_DNS_ADDRESS>
A prompt should appear asking whether we want to proceed with connecting. Type in yes
to continue. If the credentials are valid, the EC2 instance terminal will appear, thus confirming that we’ve successfully launched an EC2 instance using the AWS SDK for JavaScript.