Launch ec2 intances with CloudWatch alarms

0

Hello, my goal is to launch ec2 instances from Python code. For now I’m launching them by using launch templates. I need to create an alarm for each instance but I don’t know how to assign alarm to launch template(if it is possible). Maybe there is a different approach for that?

The main idea behind alarms is that they will stop instance if it is inactive.

  • Are you using AWS SDK for Python?

preguntada hace un año236 visualizaciones
1 Respuesta
3
Respuesta aceptada

You cannot directly assign a CloudWatch alarm to a launch template. However, you can create the alarm after launching the instance using the boto3 library in Python. Here's a step-by-step guide on how to launch an EC2 instance using a launch template and then create a CloudWatch alarm for each instance:

  1. First, install the boto3 library if you haven't already:
pip install boto3
  1. Launch an EC2 instance using a launch template:
import boto3

ec2 = boto3.client('ec2')

response = ec2.run_instances(
    LaunchTemplate={
        'LaunchTemplateName': 'your-launch-template-name',
        'Version': 'your-launch-template-version'
    },
    MinCount=1,
    MaxCount=1
)

instance_id = response['Instances'][0]['InstanceId']
print(f'Launched instance with ID: {instance_id}')
  1. Create a CloudWatch alarm for the launched instance:
import boto3

cloudwatch = boto3.client('cloudwatch')

# Replace 'your-instance-idle-metric' with the appropriate metric
# and 'your-comparison-operator' with the desired operator
# (e.g., 'LessThanOrEqualToThreshold')
response = cloudwatch.put_metric_alarm(
    AlarmName=f'IdleAlarm-{instance_id}',
    ComparisonOperator='your-comparison-operator',
    EvaluationPeriods=1,
    MetricName='your-instance-idle-metric',
    Namespace='AWS/EC2',
    Period=300,
    Statistic='SampleCount',
    Threshold=1.0,
    ActionsEnabled=True,
    AlarmActions=[
        'arn:aws:automate:your-region:ec2:stop'  # Replace 'your-region' with the appropriate AWS region
    ],
    AlarmDescription=f'Alarm for stopping idle instance {instance_id}',
    Dimensions=[
        {
            'Name': 'InstanceId',
            'Value': instance_id
        },
    ],
    Unit='Seconds',
    TreatMissingData='breaching'
)

print(f'Created alarm for instance {instance_id}')

The code above launches an EC2 instance using a launch template and then creates a CloudWatch alarm for the launched instance. The alarm will stop the instance when it's inactive, based on the specified metric, comparison operator, and threshold.

profile picture
EXPERTO
respondido hace un año

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas