Last active
          November 21, 2022 16:51 
        
      - 
      
- 
        Save pahud/836481ae759147d3f493d3ead1f5406a to your computer and use it in GitHub Desktop. 
    AWS CredentialProviderChain example in aws-sdk of NodeJS
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 'use strict'; | |
| var AWS = require('aws-sdk'); | |
| //var P = require('bluebird'); | |
| var aws_region = process.env['AWS_REGION'] ? process.env['AWS_REGION'] : 'us-west-2' | |
| var aws_profile = process.env['AWS_PROFILE'] ? process.env['AWS_PROFILE'] : 'default' | |
| AWS.CredentialProviderChain.defaultProviders = [ | |
| function () { return new AWS.EnvironmentCredentials('AWS'); }, | |
| function () { return new AWS.EnvironmentCredentials('AMAZON'); }, | |
| function () { return new AWS.SharedIniFileCredentials({profile: aws_profile ? aws_profile : 'default' }); }, | |
| function () { return new AWS.EC2MetadataCredentials(); } | |
| ]; | |
| var chain = new AWS.CredentialProviderChain(); | |
| chain.resolve((err, cred)=>{ | |
| AWS.config.credentials = cred; | |
| }) | |
| AWS.config.update({ region: aws_region }); | |
| /* | |
| const ec2 = P.promisifyAll(new AWS.EC2()) | |
| exports.handler = (event, context, cb) => { | |
| console.log(event) | |
| ec2.describeSecurityGroupsAsync() | |
| .then(data=> cb(null, data)) | |
| } | |
| */ | 
Let's make it support ECS :)
function () {
  if (AWS.ECSCredentials.prototype.isConfiguredForEcsCredentials()) {
    return new AWS.ECSCredentials();
  }
  return new AWS.EC2MetadataCredentials();
}
instead of
function () { return new AWS.EC2MetadataCredentials(); }
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Depending on how you're using this
gist, it may not work:chain.resolvehas a callback and anything you want to do with AWS should happen in that callback!