Code coverage report for ec2/doesInstanceExist.js

Statements: 100% (23 / 23)      Branches: 100% (8 / 8)      Functions: 100% (5 / 5)      Lines: 100% (23 / 23)      Ignored: none     

All files » ec2/ » doesInstanceExist.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88    1 1                   1 4                     1 4   4 1               4 3 3     1   1         1                                   1 4   1 2 1     1     4     2         1  
'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