ec2_metadata_credentials.js (2610B)
1 var AWS = require('../core'); 2 require('../metadata_service'); 3 4 /** 5 * Represents credentials received from the metadata service on an EC2 instance. 6 * 7 * By default, this class will connect to the metadata service using 8 * {AWS.MetadataService} and attempt to load any available credentials. If it 9 * can connect, and credentials are available, these will be used with zero 10 * configuration. 11 * 12 * This credentials class will by default timeout after 1 second of inactivity 13 * and retry 3 times. 14 * If your requests to the EC2 metadata service are timing out, you can increase 15 * these values by configuring them directly: 16 * 17 * ```javascript 18 * AWS.config.credentials = new AWS.EC2MetadataCredentials({ 19 * httpOptions: { timeout: 5000 }, // 5 second timeout 20 * maxRetries: 10, // retry 10 times 21 * retryDelayOptions: { base: 200 } // see AWS.Config for information 22 * }); 23 * ``` 24 * 25 * @see AWS.Config.retryDelayOptions 26 * 27 * @!macro nobrowser 28 */ 29 AWS.EC2MetadataCredentials = AWS.util.inherit(AWS.Credentials, { 30 constructor: function EC2MetadataCredentials(options) { 31 AWS.Credentials.call(this); 32 33 options = options ? AWS.util.copy(options) : {}; 34 options = AWS.util.merge( 35 {maxRetries: this.defaultMaxRetries}, options); 36 if (!options.httpOptions) options.httpOptions = {}; 37 options.httpOptions = AWS.util.merge( 38 {timeout: this.defaultTimeout}, options.httpOptions); 39 40 this.metadataService = new AWS.MetadataService(options); 41 this.metadata = {}; 42 }, 43 44 /** 45 * @api private 46 */ 47 defaultTimeout: 1000, 48 49 /** 50 * @api private 51 */ 52 defaultMaxRetries: 3, 53 54 /** 55 * Loads the credentials from the instance metadata service 56 * 57 * @callback callback function(err) 58 * Called when the instance metadata service responds (or fails). When 59 * this callback is called with no error, it means that the credentials 60 * information has been loaded into the object (as the `accessKeyId`, 61 * `secretAccessKey`, and `sessionToken` properties). 62 * @param err [Error] if an error occurred, this value will be filled 63 * @see get 64 */ 65 refresh: function refresh(callback) { 66 var self = this; 67 if (!callback) callback = function(err) { if (err) throw err; }; 68 69 self.metadataService.loadCredentials(function (err, creds) { 70 if (!err) { 71 self.expired = false; 72 self.metadata = creds; 73 self.accessKeyId = creds.AccessKeyId; 74 self.secretAccessKey = creds.SecretAccessKey; 75 self.sessionToken = creds.Token; 76 self.expireTime = new Date(creds.Expiration); 77 } 78 callback(err); 79 }); 80 } 81 });