'use strict'
var Bluebird = require('bluebird')
var isEmpty = require('lodash/lang/isEmpty')
/**
* Checks if the identifier is formatted like an instanceId
*
* i.e "i-e69990ea"
*
* @param identifier
* @returns {boolean}
*/
function isInstanceId (identifier) {
return /^i-[a-z0-9]{8}$/.test(identifier)
}
/**
* Builds the correct set of params depending on whether or not the
* identifier is an instanceId or a name.
*
* @param {state} instanceState
* @param {string} identifier
* @returns {object} params for the ec2.describeInstances call.
*/
function buildParams (identifier, instanceState) {
var params = {}
if (instanceState) {
params.Filters = [
{
Name: 'instance-state-name',
Values: [instanceState]
}
]
}
if (isInstanceId(identifier)) {
params.InstanceIds = [identifier]
return params
}
params.Filters = params.Filters || []
params.Filters.push({
Name: 'tag:Name',
Values: [identifier]
})
return params
}
/**
* Takes an identifier, either an InstanceId or Name Tag and returns whether the
* instance exists in any state. The second instanceState allows specification
* of the state the machine is in. Will also return false if an error is thrown
* when given an invalid or non existent instance ID.
*
* i.e
* doesInstanceExist('i-456ae390', 'running')
* Will only return true if that instance exists, and is in a running state.
*
* @param ec2
* @param {string} identifier Instance Name Tag or InstanceId
* @param instanceState
* @returns {*}
*/
function doesInstanceExist (ec2, identifier, instanceState) {
var params = buildParams(identifier, instanceState)
function inspectError (err) {
if (err.code === 'InvalidInstanceID.NotFound') {
return false
}
return Bluebird.reject(err)
}
return ec2
.describeInstancesPromised(params)
.then(function checkResult (data) {
return !isEmpty(data.Reservations)
})
.catch(inspectError)
}
module.exports = doesInstanceExist
|