1개 답변
- 최신
- 최다 투표
- 가장 많은 댓글
3
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:
- First, install the boto3 library if you haven't already:
pip install boto3
- 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}')
- 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.
Thank you! That's exactly what I needed.
관련 콘텐츠
- AWS 공식업데이트됨 2년 전
Are you using AWS SDK for Python?