# How to Create an EC2 Instance with AWS SDK

## Table of Contents

1. What is AWS SDK?
    
2. Prerequisites
    
3. Create EC2 instance with AWS SDK
    
4. References
    

### What is AWS SDK

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.

### Prerequisites

1. Installed AWS CLI;
    
2. Configured AWS CLI with `aws configure` command;
    

### Create an EC2 instance with AWS-SDK

1. Initialize a new npm project with the command:
    
    ```plaintext
    npm init -y
    ```
    
2. Install an aws-sdk package locally with the command:
    
    ```plaintext
    npm install aws-sdk
    ```
    
3. Create a `createInstance.js` file inside the project:
    
    ```plaintext
    touch createInstance.js
    ```
    
4. First, import the AWS SDK (Software Development Kit) library into your code in the file `createInstance.js`:
    
    ```plaintext
    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.
    
5. Then, update the AWS SDK configuration with the following credentials and the region:
    
    ```plaintext
    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.
    
6. Next, create an instance of the AWS EC2 service object with a specified API version:
    
    ```plaintext
    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.
    
7. Create a JS object named `instanceParams` that contain parameters to be used for creating a new Amazon EC2 instance using the AWS SDK.
    
    ```plaintext
    const instanceParams = {
        ImageId: "ami-053b0d53c279acc90",
        InstanceType: "t2.micro",
        KeyName: "demo-key",
        MinCount: 1,
        MaxCount: 1
    }
    ```
    
8. Using promises in JavaScript, create an EC2 instance with the AWS SDK:
    
    ```plaintext
    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.
    
9. Finally, run the code with the command:
    
    ```plaintext
    node createInstance.js
    ```
    
    The output is:
    
    ![](https://i.imgur.com/eSASY3Z.png align="center")
    
    Check whether the instance is running via AWS Console:
    
    ![](https://i.imgur.com/d5n5dpT.png align="center")
    

### References

1. [Creating EC2 instance from NodeJS](https://www.youtube.com/watch?v=SZH8utaT8WU)
