Access AWS Resources using IAM Role through AWS SDK of NodeJS

Shashi Badhuk
4 min readMar 22, 2022

Problem Statement

In General, to initialize NodeJS AWS-SDK we need to use the access key and the secret to configure it as per one of the methods describe below.

  1. Loaded from the shared credentials file (~/.aws/credentials)
  2. Loaded through ENV variables
    AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY
  3. Configure at AWS SDK initialization config
var AWS = require('aws-sdk');const credentials = {
accessKeyId: <AWS_ACCESS_KEY_ID>,
secretAccessKey: <AWS_SECRET_ACCESS_KEY>,
region: <REGION>
};
AWS.config.update(credentials);

In all of the above cases the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY need to be exposed to the execution machine, In some cases, it may be a security issue as per the use case. Now How we will get the AWS account permission without having these credentials 😕?

To achieve this we will use the IAM Role assignment to access the services.

Prerequisites

  1. AWS Account Access (To create IAM Role)
  2. EC2 Instance (Host the Node App and to use IAM Role)

Solution

  1. Create IAM Role
a. Select IAM from AWS Services Menu
b. Select Roles from Access Management Menu and Click on Create Role
c. Select Entity Type as AWS Service and Use Case to EC2 and Click Next
d. Select Appropriate permissions needed, In our case to test S3 select AmazonS3FullAccess and Click Next
e. Give Role Name, Description, and Review Permission and Click Create Role

2. NodeJS AWS-SDK Usage

Creating NodeJS App to use aws-sdk and perform actions on AWS resources. We will use S3 resource to
i. List buckets
ii. Create bucket
iii. List Objects in bucket
iv. Upload the file into the bucket
v. Remove file from bucket
vi. Remove Bucket

For the above requirement, we have created the app with the following directory structure and code snippets.

Directory Structure of NodeJS Application
createBucket.js
listBucket.js
listObject.js
removeBucket.js
removeobject.js
uploadS3.js

Now create myCustomFile.txt with some random text, which will be used by uploadS3 to upload file in S3

3. Verify Code without IAM Role

Now executing the node application to list bucket without having any permission config and IAM Role assignment

Error when we don’t have any IAM Role and SDK Config

4. Attach IAM Role to EC2 Instance

Select EC2 from AWS Service Menu and from instance listing select instance, select Actions > Security > Modify IAM Role

Now select the IAM Role created earlier and click save

5. Verify Code with IAM Role

After the assignment of IAM Role now its time to test the application

6. Verify Bucket on AWS Console

Similarly, we can access other AWS resources by assigning respective IAM Roles, but make sure to follow the least privilege policy as per AWS standard.

Please share this article if seems useful and feel free to comment and ask me anything. You can follow me on Linkedin and Twitter. Thanks for reading! 👍

--

--