<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Shashi Badhuk's Blogs]]></title><description><![CDATA[Shashi Badhuk's Blogs]]></description><link>https://blogs.shashibadhuk.in</link><generator>RSS for Node</generator><lastBuildDate>Fri, 24 Apr 2026 12:51:09 GMT</lastBuildDate><atom:link href="https://blogs.shashibadhuk.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Access AWS Resources using IAM Role through AWS SDK of NodeJS]]></title><description><![CDATA[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 variabl...]]></description><link>https://blogs.shashibadhuk.in/access-aws-resources-using-iam-role-through-aws-sdk-of-nodejs</link><guid isPermaLink="true">https://blogs.shashibadhuk.in/access-aws-resources-using-iam-role-through-aws-sdk-of-nodejs</guid><category><![CDATA[AWS]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[sdk]]></category><category><![CDATA[Amazon S3]]></category><dc:creator><![CDATA[Shashi Badhuk]]></dc:creator><pubDate>Wed, 23 Mar 2022 11:15:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1648032244891/ST5F1IVDr.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem Statement</h3>
<p>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.</p>
<ol>
<li>Loaded from the shared credentials file (~/.aws/credentials)</li>
<li>Loaded through ENV variables<ul>
<li>AWS_ACCESS_KEY_ID</li>
<li>AWS_SECRET_ACCESS_KEY</li>
</ul>
</li>
<li>Configure at AWS SDK initialization config</li>
</ol>
<pre><code><span class="hljs-keyword">var</span> AWS <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);
const credentials <span class="hljs-operator">=</span> {
  accessKeyId: <span class="hljs-operator">&lt;</span>AWS_ACCESS_KEY_ID<span class="hljs-operator">&gt;</span>,
  secretAccessKey: <span class="hljs-operator">&lt;</span>AWS_SECRET_ACCESS_KEY<span class="hljs-operator">&gt;</span>,
  region: <span class="hljs-operator">&lt;</span>REGION<span class="hljs-operator">&gt;</span>
};
AWS.config.update(credentials);
</code></pre><p>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?</p>
<p>To achieve this we will use the IAM Role assignment to access the services.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>AWS Account Access (To create IAM Role)</li>
<li>EC2 Instance (Host the Node App and to use IAM Role)</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<h4 id="heading-1-create-iam-role">1. Create IAM Role</h4>
<p>a. Select IAM from AWS Services Menu
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648032244891/ST5F1IVDr.png" alt="aws-iam.png" /></p>
<p>b. Select Roles from Access Management Menu and Click on Create Role
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648032301765/7BndwNkyW.png" alt="aws-iam-roles-add.png" /></p>
<p>c.  Select Entity Type as AWS Service and Use Case to EC2 and Click Next
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648032338048/3ePbKaVck.png" alt="aws-iam-role-create.png" /></p>
<p>d. Select Appropriate permissions needed, In our case to test S3 select AmazonS3FullAccess and Click Next
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648032370050/O-A7yQapr.png" alt="aws-iam-role-create-permissions.png" /></p>
<p>e. Give Role Name, Description, and Review Permission and Click Create Role
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648032401747/k5KLrVHcq.png" alt="aws-iam-role-create-final.png" /></p>
<h4 id="heading-2-nodejs-aws-sdk-usage">2. NodeJS AWS-SDK Usage</h4>
<p>Creating NodeJS App to use aws-sdk and perform actions on AWS resources. We will use S3 resource to</p>
<ul>
<li>i. List buckets</li>
<li>ii. Create bucket</li>
<li>iii. List Objects in bucket</li>
<li>iv. Upload the file into the bucket</li>
<li>v. Remove file from bucket</li>
<li>vi. Remove Bucket</li>
</ul>
<p>For the above requirement, we have created the app with the following directory structure and code snippets.</p>
<blockquote>
<p>Directory Structure of NodeJS Application
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648032540423/YUthfrdIB.png" alt="s3-filestructures.png" /></p>
</blockquote>
<h5 id="heading-a-listbucketjs">a. listBucket.js</h5>
<pre><code><span class="hljs-comment">// Load the AWS SDK for Node.js</span>
<span class="hljs-keyword">var</span> AWS <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>); 

<span class="hljs-comment">// Set the region </span>
AWS.config.update({region: <span class="hljs-string">'ap-southeast-1'</span>}); 

<span class="hljs-comment">// Create S3 service object </span>
s3 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> AWS.S3({apiVersion: <span class="hljs-string">'2006-03-01'</span>});

<span class="hljs-comment">// Call S3 to list the buckets </span>
s3.listBuckets(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{ 
  <span class="hljs-keyword">if</span> (err) { 
    console.log(<span class="hljs-string">"Error"</span>, err); 
  } <span class="hljs-keyword">else</span> { 
    console.log(<span class="hljs-string">"Success"</span>, data.Buckets);   
  } 
});
</code></pre><h4 id="heading-b-createbucketjs">b. createBucket.js</h4>
<pre><code><span class="hljs-comment">// Load the AWS SDK for Node.js</span>
<span class="hljs-keyword">var</span> AWS <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);
<span class="hljs-comment">// Set the region</span>
AWS.config.update({region: <span class="hljs-string">'ap-southeast-1'</span>});

<span class="hljs-comment">// Create S3 service object</span>
s3 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> AWS.S3({apiVersion: <span class="hljs-string">'2006-03-01'</span>});

<span class="hljs-comment">// Create the parameters for calling createBucket</span>
<span class="hljs-keyword">var</span> bucketParams <span class="hljs-operator">=</span> {
  Bucket : <span class="hljs-string">'shashibadhuk-test-bucket-demo-22'</span>
};

<span class="hljs-comment">// call S3 to create the bucket</span>
s3.createBucket(bucketParams, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{
  <span class="hljs-keyword">if</span> (err) {
    console.log(<span class="hljs-string">"Bucket Creation Error"</span>, err);
  } <span class="hljs-keyword">else</span> {
    console.log(`Bucket ${bucketParams.Bucket} <span class="hljs-keyword">is</span> created`, data.Location);
  }
});
</code></pre><h4 id="heading-c-listbucketjs">c. listBucket.js</h4>
<pre><code><span class="hljs-comment">// Load the AWS SDK for Node.js</span>
<span class="hljs-keyword">var</span> AWS <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);
<span class="hljs-comment">// Set the region </span>
AWS.config.update({region: <span class="hljs-string">'ap-southeast-1'</span>});

<span class="hljs-comment">// Create S3 service object</span>
s3 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> AWS.S3({apiVersion: <span class="hljs-string">'2006-03-01'</span>});

<span class="hljs-comment">// Create the parameters for calling listObjects</span>
<span class="hljs-keyword">var</span> bucketParams <span class="hljs-operator">=</span> {
  Bucket : <span class="hljs-string">'shashibadhuk-test-bucket-demo-22'</span>,
};

<span class="hljs-comment">// Call S3 to obtain a list of the objects in the bucket</span>
s3.listObjects(bucketParams, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{
  <span class="hljs-keyword">if</span> (err) {
    console.log(<span class="hljs-string">"Error"</span>, err);
  } <span class="hljs-keyword">else</span> {
    console.log(<span class="hljs-string">"Success"</span>, data);
  }
});
</code></pre><h4 id="heading-d-uploads3js">d. uploadS3.js</h4>
<pre><code><span class="hljs-comment">// Load the AWS SDK for Node.js</span>
<span class="hljs-keyword">var</span> AWS <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);
<span class="hljs-comment">// Set the region </span>
AWS.config.update({region: <span class="hljs-string">'ap-southeast-1'</span>});

<span class="hljs-comment">// Create S3 service object</span>
<span class="hljs-keyword">var</span> s3 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> AWS.S3({apiVersion: <span class="hljs-string">'2006-03-01'</span>});

<span class="hljs-comment">// call S3 to retrieve upload file to specified bucket</span>
<span class="hljs-keyword">var</span> uploadParams <span class="hljs-operator">=</span> {
  Bucket: <span class="hljs-string">'shashibadhuk-test-bucket-demo-22'</span>, 
  Key: <span class="hljs-string">''</span>, 
  Body: <span class="hljs-string">''</span>
};
<span class="hljs-keyword">var</span> file <span class="hljs-operator">=</span> <span class="hljs-string">'myCustomFile.txt'</span>;

<span class="hljs-comment">// Configure the file stream and obtain the upload parameters</span>
<span class="hljs-keyword">var</span> fs <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">var</span> fileStream <span class="hljs-operator">=</span> fs.createReadStream(file);
fileStream.on(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
  console.log(<span class="hljs-string">'File Error'</span>, err);
});
uploadParams.Body <span class="hljs-operator">=</span> fileStream;
<span class="hljs-keyword">var</span> path <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);
uploadParams.Key <span class="hljs-operator">=</span> path.basename(file);

<span class="hljs-comment">// call S3 to retrieve upload file to specified bucket</span>
s3.upload (uploadParams, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, data</span>) </span>{
  <span class="hljs-keyword">if</span> (err) {
    console.log(`File ${file} Upload <span class="hljs-built_in">Error</span>`, err);
  } <span class="hljs-keyword">if</span> (data) {
    console.log(`File ${file} Uploaded on Bucket ${uploadParams.Bucket} `, data.Location);
  }
});
</code></pre><h4 id="heading-e-removeobjectjs">e. removeObject.js</h4>
<pre><code><span class="hljs-comment">// Load the AWS SDK for Node.js</span>
<span class="hljs-keyword">var</span> AWS <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);
<span class="hljs-comment">// Set the region</span>
AWS.config.update({region: <span class="hljs-string">'ap-southeast-1'</span>});

<span class="hljs-comment">// Create S3 service object</span>
s3 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> AWS.S3({apiVersion: <span class="hljs-string">'2006-03-01'</span>});

<span class="hljs-comment">// Create params for S3.deleteBucket</span>
<span class="hljs-keyword">var</span> bucketParams <span class="hljs-operator">=</span> {
  Bucket: <span class="hljs-string">'shashibadhuk-test-bucket-demo-22'</span>,
  Key: <span class="hljs-string">'myCustomFile.txt'</span>
};

s3.deleteObject(bucketParams, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{
  <span class="hljs-keyword">if</span> (err) 
    console.log(err, err.stack); <span class="hljs-comment">// an error occurred</span>
  <span class="hljs-keyword">else</span>    
    console.log(data);           <span class="hljs-comment">// successful response</span>
});
</code></pre><h4 id="heading-f-removebucketjs">f. removeBucket.js</h4>
<pre><code><span class="hljs-comment">// Load the AWS SDK for Node.js</span>
<span class="hljs-keyword">var</span> AWS <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);
<span class="hljs-comment">// Set the region</span>
AWS.config.update({region: <span class="hljs-string">'ap-southeast-1'</span>});

<span class="hljs-comment">// Create S3 service object</span>
s3 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> AWS.S3({apiVersion: <span class="hljs-string">'2006-03-01'</span>});

<span class="hljs-comment">// Create params for S3.deleteBucket</span>
<span class="hljs-keyword">var</span> bucketParams <span class="hljs-operator">=</span> {
  Bucket : <span class="hljs-string">'shashibadhuk-test-bucket-demo-22'</span>
};

<span class="hljs-comment">// Call S3 to delete the bucket</span>
s3.deleteBucket(bucketParams, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{
  <span class="hljs-keyword">if</span> (err) {
    console.log(<span class="hljs-string">"Error"</span>, err);
  } <span class="hljs-keyword">else</span> {
    console.log(<span class="hljs-string">"Success"</span>, data);
  }
});
</code></pre><p>Now create myCustomFile.txt with some random text, which will be used by uploadS3 to upload file in S3</p>
<h4 id="heading-3-verify-code-without-iam-role">3. Verify Code without IAM Role</h4>
<p>Now executing the node application to list bucket without having any permission config and IAM Role assignment</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648033525219/30pCngvun.png" alt="Screenshot 2022-03-22 at 4.54.13 PM.png" /></p>
<h4 id="heading-4-attach-iam-role-to-ec2-instance">4. Attach IAM Role to EC2 Instance</h4>
<p>Select EC2 from AWS Service Menu and from instance listing select instance, select Actions &gt; Security &gt; Modify IAM Role</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648033606367/N-uZcN-NN.png" alt="aws-modify-iam-menu.png" /></p>
<p>Now select the IAM Role created earlier and click save</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648033637946/_oWcK7nBD.png" alt="aws-modify-iam-role.png" /></p>
<h4 id="heading-5-verify-code-with-iam-role">5. Verify Code with IAM Role</h4>
<p>After the assignment of IAM Role now its time to test the application
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648033864793/LbYq9afVv.png" alt="output.png" /></p>
<h4 id="heading-6-verify-bucket-on-aws-console">6. Verify Bucket on AWS Console</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648033730249/Q89QgkL58.png" alt="Screenshot 2022-03-22 at 5.05.31 PM.png" /></p>
<p>Similarly, we can access other AWS resources by assigning respective IAM Roles, but make sure to follow least privilege as per AWS standard.</p>
<p>Please share this article if seems useful and connect with me on <a target="_blank" href="https://www.linkedin.com/in/shashibadhuk/">linkedin</a>.</p>
<p>If you find this helpful, then please support me by <a target="_blank" href="https://www.buymeacoffee.com/shashibadhuk">buying a coffee</a>.</p>
]]></content:encoded></item></channel></rss>