AWS EC2 IAM Role Credentials

Viewed 3296

Using the Node sdk for AWS, I'm trying to use the credentials and permissions given by the IAM role that is attached to the EC2 instance that my Node application is running on.

According to the sdk documentation, that can be done using the EC2MetadataCredentials class to assign the configuration properties for the sdk.

In the file that I'm using the sdk in to access a DynamoDB instance, I have the configuration code:

import AWS from 'aws-sdk'

AWS.config.region = 'us-east-1'
AWS.config.credentials = new AWS.EC2MetadataCredentials({
    httpOptions: { timeout: 5000 },
    maxRetries: 10,
    retryDelayOptions: { base: 200 }
})

const dynamodb = new AWS.DynamoDB({
    endpoint: 'https://dynamodb.us-east-1.amazonaws.com',
    apiVersion: '2012-08-10'
})

However, when I trying to visit the web application I always get an error saying:

Uncaught TypeError: d.default.EC2MetadataCredentials is not a constructor

Uncaught TypeError: _awsSdk2.default.EC2MetadataCredentials is not a constructor

Even though that is the exact usage from the documentation! Is there something small that I'm missing?


Update:

Removing the credentials and region definitions from the file result in another error that'll say:

Error: Missing region|credentials in config

2 Answers

I don't know if this is still relevant for you, but you do need to configure the EC2MetadataCredentials as it is not in the default ProviderChain ( search for new AWS.CredentialProviderChain([ in node_loader.js in the sdk).
It seems you might have an old version of aws_sdk as that code works for me:

import AWS from 'aws-sdk';
...
AWS.config.credentials = new AWS.EC2MetadataCredentials();

I was facing a similar issue where AWS SDK was not fetching credentials. According to the documentation, SDK should be able to automatically fetch the credentials.

If you configure your instance to use IAM roles, the SDK automatically selects the IAM credentials for your application, eliminating the need to manually provide credentials.

I was able to solve the issue by manually fetching the credentials, and providing them directly wherever required (For MongoDB Atlas in my case):

var AWS = require("aws-sdk");

AWS.config.getCredentials(function(err) {
  if (err) console.log(err.stack);
  // credentials not loaded
  else {
    console.log("Access key:", AWS.config.credentials.accessKeyId);
  }
});

Source: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/global-config-object.html

Although, why SDK is not not doing it automatically is still mystery to me. I will update the answer once I figure it out.

Related