Direkt zum Inhalt

Kill EC2 automatically after lunch EC2 with EC2 Image Builder

0

I lunch EC2 with EC2 Image Builder for testing and after all stable I need to kill this EC2 automatically.

gefragt vor 2 Jahren449 Aufrufe
3 Antworten
1
Akzeptierte Antwort

This approach uses CloudWatch Events to trigger a Lambda function that performs the termination, ensuring efficient resource management and cost control.

To automatically terminate an EC2 instance after launching it with EC2 Image Builder, you can use AWS Lambda along with AWS CloudWatch Events (now part of Amazon EventBridge) to set up an automatic termination process. could you follow the below step in doing that :-

First, set up your EC2 Image Builder pipeline to create and launch the EC2 instance. Make sure the pipeline creates the instance for testing purposes.

Create a CloudWatch Event Rule that triggers when the EC2 instance reaches the running state.

Open the Amazon CloudWatch console and navigate to Rules under the Events section. Click Create rule. In the Event Source section, select Event Source and choose EC2. Choose Specific state(s) and select running. In the Targets section, click Add target and choose Lambda function. Select Create a new Lambda function.

Create an AWS Lambda Function .Create a Lambda function that terminates the EC2 instance. Here is a sample Lambda function that you can use:

Open the AWS Lambda console and create a new function. Choose Author from scratch.Enter a function name and select a runtime (e.g., Python 3.8). Create a new role with basic Lambda permissions. Use the following code for the Lambda function:

import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    
    # Extract the instance ID from the event
    instance_id = event['detail']['instance-id']
    
    # Terminate the instance
    ec2.terminate_instances(InstanceIds=[instance_id])
    
    return {
        'statusCode': 200,
        'body': f'Terminated instance {instance_id}'
    }
Save the function.
Step 4: Add Permissions to Lambda Role
Ensure the Lambda execution role has the necessary permissions to terminate EC2 instances:

In the IAM console, find the role created for your Lambda function.
Attach the following policy to the role:
json
Copia codice
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:TerminateInstances",
                "ec2:DescribeInstances"
            ],
            "Resource": "*"
        }
    ]
}

Start the EC2 Image Builder pipeline. Ensure the EC2 instance is launched. Verify that the instance is terminated automatically after being launched and tested.

EXPERTE
beantwortet vor 2 Jahren
EXPERTE
überprüft vor 2 Jahren
EXPERTE
überprüft vor 2 Jahren
1

hi

check these steps to resolve

EC2 Image Builder itself isn't designed to automatically terminate EC2 instances. Here are two approaches to achieve what you want:

  1. Leverage AWS Instance Scheduler:

This service lets you define schedules to start and stop EC2 instances. You can configure a schedule to stop the instance after your typical lunch time. Here's a helpful guide to get you started: AWS Instance Scheduler Implementation Guide

  1. Script-based Termination on the EC2 Instance:

Set the EC2 instance's "Shutdown Behavior" parameter to "Terminate" during launch. Within your instance's startup script (e.g., user data), include logic to terminate the instance after a specific time (lunchtime). This could involve: Using the aws command-line tool (pre-installed on EC2) with appropriate IAM permissions to call the TerminateInstances API. Scheduling a script execution at lunchtime using cron that calls the shutdown command.

EXPERTE
beantwortet vor 2 Jahren
EXPERTE
überprüft vor 2 Jahren
1

1. AWS Instance Scheduler:

This service allows you to define schedules for starting and stopping EC2 instances. You can configure a schedule to stop the instance at a specific time after lunch, say, a couple of hours after your usual lunch break. Here's a breakdown:

Deploy the AWS Instance Scheduler using CloudFormation.

Define a schedule in DynamoDB (a NoSQL database service) that specifies the stop time (after lunch). Tag your EC2 instance with a label indicating it should be stopped based on the schedule. After lunch, the scheduler will automatically stop the instance based on the defined schedule.

Pros:

Easy to set up and manage schedules. Cost-effective by automatically stopping unused instances. Cons:

Requires additional configuration with CloudFormation and DynamoDB.

**2. Script-based Shutdown: ** Launch your EC2 instance with an IAM role that allows it to terminate itself.

Within the instance, create a script that checks the time and shuts down the instance using the aws ec2 terminate-instances command with the AWS CLI after a designated time (lunch time + buffer).

You can use cron jobs (a scheduling tool in Linux) to trigger the script at the desired time.

Pros:

Relatively simple to implement on the EC2 instance itself.

Cons:

Requires managing IAM roles and scripts within the instance.

Might require additional development effort compared to Instance Scheduler.

Choosing the right approach depends on your technical expertise and preference. Here are some resources to get you started:

AWS Instance Scheduler:https://aws.amazon.com/solutions/implementations/instance-scheduler-on-aws Automatically stop EC2 instances: https://aws.amazon.com/solutions/implementations/instance-scheduler-on-aws/ AWS CLI terminate-instances: https://docs.aws.amazon.com/cli/latest/reference/ec2/terminate-instances.html

EXPERTE
beantwortet vor 2 Jahren
EXPERTE
überprüft vor 2 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.