Skip to content

NodeJS SDK

Created: 2016-02-10 10:19:57 -0800 Modified: 2018-11-14 09:49:23 -0800

  • Make a credentials file at ~/.aws/credentials (or on Windows: %userprofile%\awscredentials) - note: ‘credentials’ is the name of the file, not a folder.

[default]

aws_access_key_id = <YOUR_ACCESS_KEY_ID>

aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>

To test your setup without costing money, just copy/paste this code in:

const AWS = require(‘aws-sdk’);

AWS.config.region = ‘us-west-2’;

var s3 = new AWS.S3();

s3.listBuckets(function(err, data) {

if (err) {

console.log(“Error:”, err);

} else {

if (data.Buckets.length === 0) {

console.log(‘You are a sad sealion.’);

}

for (var index in data.Buckets) {

var bucket = data.Buckets[index];

console.log(“Bucket: ”, bucket.Name, ’ : ’, bucket.CreationDate);

}

}

});

Useful API doc snippets (i.e. not full scripts)

Section titled Useful API doc snippets (i.e. not full scripts)

Specify a private IP. Put this at the top-level of params:

PrivateIpAddress: ‘10.0.0.4’

To filter, do something like this:

const params = {

‘Filters’: [

{

Name: ‘instance-state-name’,

Values: [‘running’]

},

{

Name: ‘tag:type ’, // the part after the colon is the key for your tag. You can specify multiple allowed values in the array below, but you can’t have another filter with the same tag key (and you wouldn’t want to since it doesn’t accomplish anything you can’t do with just the Values property below). Note: tags are case-sensitive.

Values: [‘Overseer #2’] // this is the value for your tag

}

]

};

ec2.describeInstances(params, function(err, data) { /_ … _/ });

Describe all EC2 instances (useful for getting their IDs)

Section titled Describe all EC2 instances (useful for getting their IDs)

const AWS = require(‘aws-sdk’);

AWS.config.region = ‘us-west-2’;

var ec2 = new AWS.EC2();

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);

}

}

}

});

const AWS = require(‘aws-sdk’);

AWS.config.region = ‘us-west-2’;

var ec2 = new AWS.EC2();

var params = {

InstanceIds: [

‘i-7815d4a0’

],

DryRun: false

};

ec2.terminateInstances(params, function(err, data) {

if (err) console.log(err, err.stack); // an error occurred

else console.log(data); // successful response

});

Instance a new VM (assuming you still have a default VPC)

Section titled Instance a new VM (assuming you still have a default VPC)

const AWS = require(‘aws-sdk’);

AWS.config.region = ‘us-west-2’;

var ec2 = new AWS.EC2();

var params = {

// The Amazon Linux AMI is an EBS-backed, AWS-supported image. The default

// image includes AWS command line tools, Python, Ruby, Perl, and Java. The

// repositories include Docker, PHP, MySQL, PostgreSQL, and other packages.

ImageId: ‘ami-f0091d91’,

// If true and everything WOULD have succeeded, you’ll instead see

// “DryRunOperation” as the error message. However, it won’t actually

// perform any real actions other than testing whether you COULD do

// something.

DryRun: false,

InstanceType: ‘t2.micro’,

// You get this from the EC2 console and then go to Network & Security —>

// Key Pairs.

KeyName: ‘First key pair’,

// You can find these in the EC2 console —> Network & Security —> Security

// Groups. You list these by name. If you want, there’s a different param

// called SecurityGroupIds that lets you specify by ID.

SecurityGroups: [‘launch-wizard-1’], // this particular group is for SSH

// If false, you’re allowed to terminate this via API or console. If true,

// you can’t terminate this until setting it back to false later.

DisableApiTermination: false,

// If ‘stop’, your instance will simply turn off and stop charging money for

// CPU time (but still charge money for EBS (storage) and maybe IP addresses

// used). If ‘terminate’, your instance will be deleted entirely along with

// any EBS.

InstanceInitiatedShutdownBehavior: ‘terminate’,

// If true, this may cost more money, but it will be better optimized for

// EBS.

EbsOptimized: false,

Monitoring: {

Enabled: false

},

MinCount: 1,

MaxCount: 1

};

// Create the instance

ec2.runInstances(params, function(err, data) {

if (err) {

console.log(‘Could not create instance’, err);

return;

}

var instanceId = data.Instances[0].InstanceId;

console.log(‘Created instance’, instanceId);

// Add tags to the instance

params = {

Resources: [instanceId],

Tags: [{

Key: ‘Name’,

Value: ‘instanceName’

}]

};

ec2.createTags(params, function(err) {

console.log(‘Tagging instance’, err ? ‘failure’ :

‘success’);

});

});

function testSetDns() {

const route53 = new AWS.Route53();

const params = {

ChangeBatch: { /_ required _/

Changes: [ /_ required _/ {

Action: ‘UPSERT’,

/_ required _/

ResourceRecordSet: { /_ required _/

Name: ‘overseer.bot.land’,

/_ required _/

Type: ‘A’,

/_ required _/

ResourceRecords: [{

Value: ‘10.0.0.7’ /_ required _/

}],

TTL: 0,

}

},

],

},

HostedZoneId: ‘ZA729ONCYRM02’ /_ required _/

};

route53.changeResourceRecordSets(params, function(err, data) {

if (err) console.log(err, err.stack); // an error occurred

else console.log(‘Done changing record sets: ’ + data); // successful response

});

}

Fetch instance ID from metadata service

Section titled Fetch instance ID from metadata service

// Note: this requires bluebird const Promise = require(‘bluebird’);

function getInstanceId() {

const metadataService = new AWS.MetadataService();

const promisifiedRequest = Promise.promisify(metadataService.request, {context: metadataService});

return promisifiedRequest(‘/latest/meta-data/instance-id’);

}

getInstanceId()

.then((instanceId) => {

console.log(‘Your instance ID is: ’ + instanceId);

})

.catch((error) => {

console.error(‘Got error: ’ + error);

});