Skip to content

Instantly share code, notes, and snippets.

@d5
Last active October 6, 2022 07:30
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save d5/8345619 to your computer and use it in GitHub Desktop.
Save d5/8345619 to your computer and use it in GitHub Desktop.
AWS Node.js SDK; EC2 instance creation and termination example
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);
}
}
});
}
@ardname
Copy link

ardname commented Oct 3, 2017

Hi!

How to create Instance in defined VPC. I've faced with a problem when no default VPC created I can't make createServer or createInstance.
Response is : http://joxi.ru/Dr8aXGyskvGLOm
Thanks for reply in advance.

@jawadabbasi54
Copy link

How i identify the creation of AWS ec2 instance ....? May i differ between the ec2 instance creation and running state..?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment