Created
August 26, 2016 09:58
-
-
Save tzechienchu/66d34e1744cab0162d0e5f46d818268c to your computer and use it in GitHub Desktop.
AWS Node.js SDK; EC2 instance creation and termination example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var aws = require('aws-sdk'); | |
aws.config.update({ | |
accessKeyId: 'YOUR_ACCESS_KEY', | |
secretAccessKey: 'YOUR_SECRET_KEY', | |
region: 'us-west-2' | |
}); | |
var ec2 = new aws.EC2(); | |
function printStatuses() { | |
ec2.describeInstances({}, function(err, data) { | |
if(err) { | |
console.error(err.toString()); | |
} else { | |
var currentTime = new Date(); | |
console.log(currentTime.toString()); | |
for(var r=0,rlen=data.Reservations.length; r<rlen; r++) { | |
var reservation = data.Reservations[r]; | |
for(var i=0,ilen=reservation.Instances.length; i<ilen; ++i) { | |
var instance = reservation.Instances[i]; | |
var name = ''; | |
for(var t=0,tlen=instance.Tags.length; t<tlen; ++t) { | |
if(instance.Tags[t].Key === 'Name') { | |
name = instance.Tags[t].Value; | |
} | |
} | |
console.log('\t'+name+'\t'+instance.InstanceId+'\t'+instance.PublicIpAddress+'\t'+instance.InstanceType+'\t'+instance.ImageId+'\t'+instance.State.Name); | |
} | |
} | |
} | |
}); | |
} | |
function createInstance(imageId, count, keyPair, securityGroup, instanceType) { | |
ec2.runInstances({ | |
ImageId: imageId, | |
MinCount: count, | |
MaxCount: count, | |
KeyName: keyPair, | |
SecurityGroups: [securityGroup], | |
InstanceType: instanceType | |
}, function(err, data) { | |
if(err) { | |
console.error(err.toString()); | |
} else { | |
for(var i in data.Instances) { | |
var instance = data.Instances[i]; | |
console.log('NEW:\t' + instance.InstanceId); | |
} | |
} | |
}); | |
} | |
function terminateInstance(instanceId) { | |
ec2.terminateInstances({ InstanceIds: [instanceId] }, function(err, data) { | |
if(err) { | |
console.error(err.toString()); | |
} else { | |
for(var i in data.TerminatingInstances) { | |
var instance = data.TerminatingInstances[i]; | |
console.log('TERM:\t' + instance.InstanceId); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment