How to use the EC2 function from aws-sdk

Find comprehensive JavaScript aws-sdk.EC2 code examples handpicked from public code repositorys.

aws-sdk.EC2 is a class in the AWS SDK that provides methods for working with Amazon EC2 instances and related resources.

1
2
3
4
5
6
7
8
9
10
 * Created by waylau on 2016/8/6.
 */
var AWS = require('aws-sdk');
exports.handler = function (event, context) {
    console.log("Received data as:", event);
    var ec2 = new AWS.EC2({region: 'ap-northeast-1'});
    var params = {
        ImageId: 'ami-29160d47',
        InstanceType: 't2.micro',
        KeyName: 'Tech-labs',
fork icon102
star icon347
watch icon43

+ 3 other calls in file

57
58
59
60
61
62
63
64
65
66
67
68
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: 'us-east-2',
});


const autoscaling = new AWS.AutoScaling();
const ec2 = new AWS.EC2();


const fetchWithTimeout = async (url, options, timeout = 5000) => {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);
fork icon99
star icon159
watch icon9

+ 45 other calls in file

How does aws-sdk.EC2 work?

In the AWS SDK, aws-sdk.EC2 is a class that provides methods for working with Amazon Elastic Compute Cloud (EC2) instances and related resources. EC2 is a web service that provides resizable compute capacity in the cloud, allowing you to quickly scale your applications up or down as needed. Using aws-sdk.EC2, you can programmatically create, launch, and manage EC2 instances, as well as interact with other EC2 resources such as security groups, key pairs, and EBS volumes. You can also perform operations such as starting, stopping, and terminating instances, and retrieving information about instances, images, and availability zones. To use aws-sdk.EC2, you first need to authenticate with AWS by providing your AWS access keys. You can then create a new instance of the aws-sdk.EC2 class, specifying your AWS region and any other options or configuration settings. Once you have a new instance of aws-sdk.EC2, you can call various methods to interact with EC2 resources. For example, you might call runInstances to create and launch new EC2 instances, or describeInstances to retrieve information about existing instances. Many of the methods provided by aws-sdk.EC2 return promises, allowing you to use async/await or promise chaining to handle the results of API calls. For example, here's how you might use aws-sdk.EC2 to retrieve information about all running instances in your AWS account: javascript Copy code {{{{{{{ const AWS = require('aws-sdk'); const ec2 = new AWS.EC2({ region: 'us-east-1' }); ec2.describeInstances({ Filters: [{ Name: 'instance-state-name', Values: ['running'] }] }, (err, data) => { if (err) { console.error(err); } else { console.log(data); } }); In this example, we're creating a new instance of the aws-sdk.EC2 class, specifying the us-east-1 region. We're then calling the describeInstances method to retrieve information about all running instances in our account, using a filter to specify that we only want to retrieve instances with a state of "running". We pass a callback function to describeInstances that will be called with the results of the API call. If there's an error, we log it to the console using console.error. Otherwise, we log the data returned by the API call to the console using console.log. Overall, aws-sdk.EC2 is a powerful class in the AWS SDK that allows you to programmatically interact with Amazon EC2 instances and related resources, making it easier to manage and scale your applications in the cloud.

74
75
76
77
78
79
80
81
82
83

console.log("Triggered");
console.log(event);
console.log(context);

var ec2 = new AWS.EC2();
var cloudwatchevents = new AWS.CloudWatchEvents();
var lambda = new AWS.Lambda();
var ImageId;
var RuleArn;
fork icon19
star icon122
watch icon7

20
21
22
23
24
25
26
27
28
29
    if (input.creds)  params.credentials = input.creds;
    else if (input.profile) {
        var credentials = new AWS.SharedIniFileCredentials({profile: input.profile});
        AWS.config.credentials = credentials;
    }
    var ec2 = new AWS.EC2(params);
    return ec2;
}

me.securityGroupHasRules = function(input, callback) {
fork icon6
star icon29
watch icon21

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const AWS = require("aws-sdk");
const ec2 = new AWS.EC2({ region: "us-east-1" });

const params = {
  ImageId: "ami-0c55b159cbfafe1f0",
  InstanceType: "t2.micro",
  KeyName: "my-key-pair",
  MinCount: 1,
  MaxCount: 1,
};

ec2.runInstances(params, (err, data) => {
  if (err) {
    console.error(err);
  } else {
    console.log(data);
  }
});

In this example, we're creating a new instance of the aws-sdk.EC2 class, specifying the us-east-1 region. We're then defining an object params that specifies the configuration for the new EC2 instance. The ImageId parameter specifies the ID of the Amazon Machine Image (AMI) to use for the instance, while the InstanceType parameter specifies the type of instance to launch. We also specify a KeyName parameter that references an existing EC2 key pair to use for SSH access to the instance. We then call the runInstances method, passing in the params object and a callback function that will be called with the results of the API call. If there's an error, we log it to the console using console.error. Otherwise, we log the data returned by the API call to the console using console.log. When you run this code, you'll see that a new EC2 instance is launched in your AWS account, using the configuration specified in the params object. The data object returned by the runInstances method contains information about the new instance, including its instance ID, launch time, and public IP address (if applicable).

-2
-1
module.exports.iam = new AWS.IAM();
module.exports.configService = new AWS.ConfigService();
fork icon7
star icon21
watch icon6

475
476
477
478
479
480
481
482
483
484
  console.log('Create stack set...');
  await this.cloudFormationClient.createStackSet(stackParameters).promise();
}

const currentStackData = await this.cloudFormationClient.describeStackSet({ StackSetName: options.stackSetName }).promise().then(data => data.StackSet);
const rawRegions = await new EC2().describeRegions().promise().then(data => data.Regions.map(r => r.RegionName));
const newRegions = rawRegions.filter(r => !currentStackData.Regions || !currentStackData.Regions.some(e => e === r))
.filter(r => r !== 'eu-central-2' && r !== 'ap-south-2' && r !== 'eu-south-2' && r !== 'me-central-1' && r !== 'ap-southeast-4');

// If the stack already existed, and there are no new regions, all the stacks are updated then check to see if the template matches the new template
fork icon4
star icon31
watch icon3

+ 11 other calls in file

70
71
72
73
74
75
76
77
78
79
} else {
    config.httpOptions = { agent: new https.Agent(opts) };
}

AWS.config.update(config);
this.ec2 = new AWS.EC2();
this.s3 = new AWS.S3();

if (this.storageName) {
    return this.storageName;
fork icon1
star icon12
watch icon16

21
22
23
24
25
26
27
28
29
30
      resolve(JSON.parse(data));
    }
  });
}).then(({ region }) => {
  return new Promise((resolve, reject) => {
    const ec2 = new AWS.EC2({ region });
    ec2.describeInstances({
      Filters: [
        {
          Name: 'tag:' + opts.awsTagName,
fork icon0
star icon1
watch icon7

51
52
53
54
55
56
57
58
59
60
61
62
  return acc;
}


function makeTablesAsync(region) {
  var public_ips_request = new url.URL('https://ip-ranges.amazonaws.com/ip-ranges.json');
  var ec2 = Promise.promisifyAll(new AWS.EC2({'region': region}));


  return Promise.all([
    ec2.describeInstancesAsync(null),
    ec2.describeNetworkInterfacesAsync(null),
fork icon0
star icon0
watch icon2

55
56
57
58
59
60
61
62
63
64
})
  .then(() => {
    const region     = metadata.region
    const instanceId = metadata.instanceId

    const ec2 = new aws.EC2({ region })

    const Name    = 'resource-id'
    const Values  = [ instanceId ]
    const Filters = [ { Name, Values } ]
fork icon0
star icon0
watch icon17