Access AWS Resources using IAM Role through AWS SDK of NodeJS
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.
- Loaded from the shared credentials file (
~/.aws/credentials
) - Loaded through ENV variables
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY - 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
- AWS Account Access (To create IAM Role)
- EC2 Instance (Host the Node App and to use IAM Role)
Solution
- Create IAM 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.
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
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! 👍