|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +'use strict'; |
| 4 | + |
| 5 | +var aws = require('aws-sdk'); |
| 6 | +var ec2 = new aws.EC2({ |
| 7 | + accessKeyId: 'AKIAJ3RCYU6FCULAJP2Q', |
| 8 | + secretAccessKey: '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', |
| 9 | + region: 'us-west-1' |
| 10 | +}); |
| 11 | + |
| 12 | +var params = { |
| 13 | + Filters: [ |
| 14 | + // Only fetch instances that are tagged as docks |
| 15 | + { |
| 16 | + Name: 'tag:role', |
| 17 | + Values: ['dock'] |
| 18 | + }, |
| 19 | + // Only fetch running instances |
| 20 | + { |
| 21 | + Name: 'instance-state-name', |
| 22 | + Values: ['running'] |
| 23 | + }, |
| 24 | + // Only fetch docks with the tag "env" equal to "staging" |
| 25 | + { |
| 26 | + Name: 'tag:env', |
| 27 | + Values: ['staging'] |
| 28 | + } |
| 29 | + ] |
| 30 | +}; |
| 31 | + |
| 32 | +ec2.describeInstances(params, function (err, data) { |
| 33 | + if (err) { |
| 34 | + console.error("An error occurred: ", err); |
| 35 | + process.exit(1); |
| 36 | + } |
| 37 | + |
| 38 | + // Get a set of instances from the describe response |
| 39 | + var instances = []; |
| 40 | + data.Reservations.forEach(function (res) { |
| 41 | + res.Instances.forEach(function (instance) { |
| 42 | + instances.push(instance); |
| 43 | + }); |
| 44 | + }); |
| 45 | + |
| 46 | + // Map the instances to their private ip addresses |
| 47 | + // NOTE This will work locally because of the wilcard ssh proxy in the config |
| 48 | + var hosts = instances.map(function (instance) { |
| 49 | + return instance.PrivateIpAddress; |
| 50 | + }); |
| 51 | + |
| 52 | + var hostVars = {}; |
| 53 | + instances.forEach(function (instance) { |
| 54 | + for (var i = 0; i < instance.Tags.length; i++) { |
| 55 | + if (instance.Tags[i].Key === 'org') { |
| 56 | + hostVars[instance.PrivateIpAddress] = { |
| 57 | + host_tags: instance.Tags[i].Value + ',build,run' |
| 58 | + }; |
| 59 | + } |
| 60 | + } |
| 61 | + }); |
| 62 | + |
| 63 | + // Output the resulting JSON |
| 64 | + // NOTE http://docs.ansible.com/ansible/developing_inventory.html |
| 65 | + console.log(JSON.stringify( |
| 66 | + { |
| 67 | + docks: { |
| 68 | + hosts: hosts |
| 69 | + }, |
| 70 | + _meta : { |
| 71 | + hostvars : hostVars |
| 72 | + } |
| 73 | + } |
| 74 | + )); |
| 75 | +}); |
0 commit comments