-
Firstly, ensure you have Node.js installed on your machine.
-
Create a new directory for your project and navigate to that directory in the command line.
-
Initialize a new Node.js project using the following command:
npm init -y
-
Install the @aws-sdk/client-ec2 package and its necessary peer dependencies:
npm install @aws-sdk/client-ec2 aws-sdk dotenv
-
Create a .env file in your project directory to store your AWS credentials. Add the following lines to the .env file, replacing <your-access-key> and <your-secret-key> with your actual AWS Access Key ID and Secret Access Key:
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-key>
-
Create a new JavaScript file (e.g., launchInstances.js) and import the required modules and packages:
require('dotenv').config();
const { EC2Client, RunInstancesCommand } = require('@aws-sdk/client-ec2');
-
Initialize the EC2 client with your AWS credentials by creating a new instance of EC2Client:
const client = new EC2Client({
region: 'us-east-1', // Replace with your desired region
});
-
Define a function to launch instances using the RunInstancesCommand. Here's an example of launching a single instance:
const runInstances = async () => {
try {
const command = new RunInstancesCommand({
InstanceType: 't2.micro', // Replace with your desired instance type
MaxCount: 1, // Number of instances to launch
MinCount: 1,
ImageId: 'ami-12345678', // Replace with your desired AMI ID
});
const response = await client.send(command);
console.log('Instances launched:', response.Instances);
} catch (error) {
console.error('Error launching instances:', error);
}
};
-
Call the runInstances function to launch the instances:
runInstances();
-
Run your JavaScript file using Node.js:
node launchInstances.js