Menu
AWS SDK for JavaScript
Developer Guide for SDK version 2.119.0

Creating an Amazon EC2 Instance


                                            Relationship between JavaScript environments, the SDK, and Lambda

This Node.js example shows you how to:

  • Create an Amazon EC2 instance from a public Amazon Machine Image (AMI)

  • Create and assign tags to the new Amazon EC2 instance

The Scenario

In this example, you use a Node.js module to create an Amazon EC2 instance and assign tags to it. The code uses the SDK for JavaScript to create and tag an instance by using these methods of the Amazon EC2 client class:

Prerequisite Tasks

To set up and run this example, first complete these tasks:

Configuring the SDK

Configure the SDK for JavaScript by creating a global configuration object, setting the region, and providing credentials for your code. In this example, you use the JSON file you created to provide the credentials.

Copy
// Load the SDK for JavaScript var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json');

Creating and Tagging an Instance

Create a Node.js module with the file name ec2_createinstances.js. Be sure to configure the SDK as previously shown. To access Amazon EC2, create an AWS.EC2 service object. Call the runInstances, method, and then call the createTags method of the Amazon EC2 service object.

The code adds a Name tag to a new instance, which the Amazon EC2 console recognizes and displays in the Name field of the instance list. You can add up to 50 tags to an instance, all of which can be added in a single call to the createTags method.

Copy
// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json'); // Create EC2 service object var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); var params = { ImageId: 'ami-10fd7020', // amzn-ami-2011.09.1.x86_64-ebs InstanceType: 't1.micro', 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: 'SDK Sample' } ]}; ec2.createTags(params, function(err) { console.log("Tagging instance", err ? "failure" : "success"); }); });

To run the example, type the following at the command line.

Copy
node ec2_createinstances.js

This sample code can be found here on GitHub.