environment_credentials.js (2944B)
1 var AWS = require('../core'); 2 3 /** 4 * Represents credentials from the environment. 5 * 6 * By default, this class will look for the matching environment variables 7 * prefixed by a given {envPrefix}. The un-prefixed environment variable names 8 * for each credential value is listed below: 9 * 10 * ```javascript 11 * accessKeyId: ACCESS_KEY_ID 12 * secretAccessKey: SECRET_ACCESS_KEY 13 * sessionToken: SESSION_TOKEN 14 * ``` 15 * 16 * With the default prefix of 'AWS', the environment variables would be: 17 * 18 * AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN 19 * 20 * @!attribute envPrefix 21 * @readonly 22 * @return [String] the prefix for the environment variable names excluding 23 * the separating underscore ('_'). 24 */ 25 AWS.EnvironmentCredentials = AWS.util.inherit(AWS.Credentials, { 26 27 /** 28 * Creates a new EnvironmentCredentials class with a given variable 29 * prefix {envPrefix}. For example, to load credentials using the 'AWS' 30 * prefix: 31 * 32 * ```javascript 33 * var creds = new AWS.EnvironmentCredentials('AWS'); 34 * creds.accessKeyId == 'AKID' // from AWS_ACCESS_KEY_ID env var 35 * ``` 36 * 37 * @param envPrefix [String] the prefix to use (e.g., 'AWS') for environment 38 * variables. Do not include the separating underscore. 39 */ 40 constructor: function EnvironmentCredentials(envPrefix) { 41 AWS.Credentials.call(this); 42 this.envPrefix = envPrefix; 43 this.get(function() {}); 44 }, 45 46 /** 47 * Loads credentials from the environment using the prefixed 48 * environment variables. 49 * 50 * @callback callback function(err) 51 * Called after the (prefixed) ACCESS_KEY_ID, SECRET_ACCESS_KEY, and 52 * SESSION_TOKEN environment variables are read. When this callback is 53 * called with no error, it means that the credentials information has 54 * been loaded into the object (as the `accessKeyId`, `secretAccessKey`, 55 * and `sessionToken` properties). 56 * @param err [Error] if an error occurred, this value will be filled 57 * @see get 58 */ 59 refresh: function refresh(callback) { 60 if (!callback) callback = function(err) { if (err) throw err; }; 61 62 if (!process || !process.env) { 63 callback(AWS.util.error( 64 new Error('No process info or environment variables available'), 65 { code: 'EnvironmentCredentialsProviderFailure' } 66 )); 67 return; 68 } 69 70 var keys = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'SESSION_TOKEN']; 71 var values = []; 72 73 for (var i = 0; i < keys.length; i++) { 74 var prefix = ''; 75 if (this.envPrefix) prefix = this.envPrefix + '_'; 76 values[i] = process.env[prefix + keys[i]]; 77 if (!values[i] && keys[i] !== 'SESSION_TOKEN') { 78 callback(AWS.util.error( 79 new Error('Variable ' + prefix + keys[i] + ' not set.'), 80 { code: 'EnvironmentCredentialsProviderFailure' } 81 )); 82 return; 83 } 84 } 85 86 this.expired = false; 87 AWS.Credentials.apply(this, values); 88 callback(); 89 } 90 91 });