Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created November 6, 2015 22:25
Show Gist options
  • Save jhurliman/b707b935b9bb84706437 to your computer and use it in GitHub Desktop.
Save jhurliman/b707b935b9bb84706437 to your computer and use it in GitHub Desktop.
Retrieve metadata about the host EC2 instance
var P = require('bluebird');
var request = P.promisify(require('request'));
P.promisifyAll(request);
exports.currentInstanceInfo = currentInstanceInfo;
var INSTANCE_BASE_URL = 'http://169.254.169.254/2014-11-05/';
currentInstanceInfo().then(res => console.dir(res));
function currentInstanceInfo() {
return P.props({
'ami-id': instanceGet('meta-data/ami-id'),
'ami-launch-index': instanceGet('meta-data/ami-launch-index'),
'ami-manifest-path': instanceGet('meta-data/ami-manifest-path'),
'availability-zone': instanceGet('meta-data/placement/availability-zone'),
'block-device-mapping': getBlockDevices(),
'instance-action': instanceGet('meta-data/instance-action'),
'instance-id': instanceGet('meta-data/instance-id'),
'instance-identity': instanceGetJSON('dynamic/instance-identity/document'),
'instance-type': instanceGet('meta-data/instance-type'),
'local-hostname': instanceGet('meta-data/local-hostname'),
'local-ipv4': instanceGet('meta-data/local-ipv4'),
'mac': instanceGet('meta-data/mac'),
'public-hostname': instanceGet('meta-data/public-hostname'),
'public-ipv4': instanceGet('meta-data/public-ipv4'),
'public-keys': getPublicKeys(),
'reservation-id': instanceGet('meta-data/reservation-id'),
'security-groups': instanceGet('meta-data/security-groups'),
'user-data': instanceGet('user-data')
});
}
function getBlockDevices() {
var BLOCK_URL = 'meta-data/block-device-mapping/';
return instanceGet(BLOCK_URL)
.then(body => body.split('\n'))
.then(aliases => {
var obj = {};
aliases.forEach(alias => obj[alias] = instanceGet(BLOCK_URL + alias));
return P.props(obj);
});
}
function getPublicKeys() {
var KEY_URL = 'meta-data/public-keys/';
return instanceGet(KEY_URL)
.then(body => body.split('\n'))
.then(indexesToNames => {
var obj = {};
indexesToNames.forEach(i2n => {
var parts = i2n.split('=');
var index = parts[0];
var name = parts[1];
obj[name] = instanceGet(KEY_URL + index + '/')
.then(body => body.split('\n'))
.then(keyTypes => {
var keys = {};
keyTypes.forEach(keyType => keys[keyType] = instanceGet(KEY_URL + index + '/' + keyType));
return P.props(keys);
});
return P.props(obj);
});
return P.props(obj);
});
}
function instanceGet(endpoint) {
return request.getAsync(INSTANCE_BASE_URL + endpoint)
.then(res => res.statusCode === 200 ? res.body : null);
}
function instanceGetJSON(endpoint) {
return request.getAsync(INSTANCE_BASE_URL + endpoint)
.then(res => JSON.parse(res.body));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment