ec2.service.tsā¢2.07 kB
import {
RunInstancesCommand,
TerminateInstancesCommand,
DescribeInstancesCommand
} from '@aws-sdk/client-ec2';
import { ec2Client } from '../../config/aws.config';
import { logger } from '../../utils/logger';
export class EC2Service {
async createInstance(parameters: any) {
try {
const command = new RunInstancesCommand({
ImageId: parameters.imageId || 'ami-0c02fb55956c7d316',
InstanceType: parameters.instanceType || 't2.micro',
MinCount: 1,
MaxCount: 1,
TagSpecifications: [
{
ResourceType: 'instance',
Tags: [
{
Key: 'Name',
Value: parameters.name || 'MCP-Created-Instance',
},
{
Key: 'CreatedBy',
Value: 'MCP-Infrastructure',
},
],
},
],
});
const response = await ec2Client.send(command);
const instanceId = response.Instances?.[0]?.InstanceId;
logger.info(`Created EC2 instance: ${instanceId}`);
return { instanceId, details: response.Instances?.[0] };
} catch (error) {
logger.error('Error creating EC2 instance:', error);
throw error;
}
}
async terminateInstance(instanceId: string) {
try {
const command = new TerminateInstancesCommand({
InstanceIds: [instanceId],
});
const response = await ec2Client.send(command);
logger.info(`Terminated EC2 instance: ${instanceId}`);
return { success: true, details: response };
} catch (error) {
logger.error('Error terminating EC2 instance:', error);
throw error;
}
}
async getInstanceStatus(instanceId: string) {
try {
const command = new DescribeInstancesCommand({
InstanceIds: [instanceId],
});
const response = await ec2Client.send(command);
return response.Reservations?.[0]?.Instances?.[0];
} catch (error) {
logger.error('Error getting instance status:', error);
throw error;
}
}
}