You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何一次性为多台EC2实例创建CPUUtilization指标告警?

Great question—manually setting up 20 CloudWatch alarms one by one is such a tedious task. Let’s cover a few practical ways to batch-create CPUUtilization alarms for all your EC2 Linux instances without the repetitive work:

1. Use AWS CLI with a Simple Loop

This is my go-to for quick batch operations. Here’s how to do it:

First, get a list of all your target EC2 instance IDs (you can filter by tags if you only want specific instances):

INSTANCE_IDS=$(aws ec2 describe-instances --filters "Name=tag:Environment,Values=Production" --query "Reservations[*].Instances[*].InstanceId" --output text)

(Replace the filter with your own tag criteria, or remove the --filters flag to get all instances in your account/region)

Then loop through each instance ID to create the alarm:

for INSTANCE in $INSTANCE_IDS; do
  aws cloudwatch put-metric-alarm \
    --alarm-name "CPU-High-Alarm-$INSTANCE" \
    --alarm-description "Alarm when CPU exceeds 80% for 2 consecutive 5-minute periods" \
    --metric-name CPUUtilization \
    --namespace AWS/EC2 \
    --statistic Average \
    --period 300 \
    --evaluation-periods 2 \
    --threshold 80 \
    --comparison-operator GreaterThanThreshold \
    --dimensions "Name=InstanceId,Value=$INSTANCE" \
    --alarm-actions "arn:aws:sns:us-east-1:123456789012:Your-Alarm-Topic" \
    --ok-actions "arn:aws:sns:us-east-1:123456789012:Your-Alarm-Topic"
done

Make sure to update the --alarm-actions ARN with your actual SNS topic ARN, and adjust threshold/period values to match your needs.

2. Use AWS CloudFormation for Infrastructure as Code

If you prefer to keep your alarms defined as code (great for reproducibility), create a CloudFormation template like this:

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  InstanceIds:
    Type: CommaDelimitedList
    Description: List of EC2 Instance IDs to create alarms for
  SNSTopicArn:
    Type: String
    Description: ARN of the SNS topic for alarm notifications
  CPUThreshold:
    Type: Number
    Default: 80
    Description: CPU utilization threshold to trigger alarm

Resources:
  CPUAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmName: !Sub "CPU-High-Alarm-${InstanceId}"
      AlarmDescription: CPU utilization exceeds threshold
      MetricName: CPUUtilization
      Namespace: AWS/EC2
      Statistic: Average
      Period: 300
      EvaluationPeriods: 2
      Threshold: !Ref CPUThreshold
      ComparisonOperator: GreaterThanThreshold
      Dimensions:
        - Name: InstanceId
          Value: !Ref InstanceId
      AlarmActions:
        - !Ref SNSTopicArn
      OKActions:
        - !Ref SNSTopicArn
    Count: !Length !Ref InstanceIds
    Iterator:
      InstanceId: !Select [!Ref Index, !Ref InstanceIds]

Deploy this template via the CloudFormation console or CLI, and pass your list of instance IDs as a parameter. This will create an alarm for each instance in the list automatically.

3. Use AWS Systems Manager Automation Runbook

If you want a no-code GUI approach, use the pre-built SSM Automation runbook:

  • Go to the AWS Systems Manager console, navigate to Automation > Execute automation
  • Search for AWS-CreateCloudWatchAlarms and select it
  • In the input parameters:
    • Specify InstanceIds (comma-separated list) or use TagFilters to target instances with specific tags
    • Set MetricName to CPUUtilization
    • Configure your threshold, period, and SNS topic ARN
  • Run the automation—it will create alarms for all matching instances in one go.
4. Custom Script with Boto3 (Python)

For more flexibility (like adding custom logic), use the AWS SDK for Python:

import boto3

cloudwatch = boto3.client('cloudwatch')
ec2 = boto3.client('ec2')

# Get all instances (or filter by tags)
response = ec2.describe_instances(Filters=[{'Name': 'tag:Environment', 'Values': ['Production']}])
instance_ids = [instance['InstanceId'] for reservation in response['Reservations'] for instance in reservation['Instances']]

# Define alarm parameters
alarm_params = {
    'MetricName': 'CPUUtilization',
    'Namespace': 'AWS/EC2',
    'Statistic': 'Average',
    'Period': 300,
    'EvaluationPeriods': 2,
    'Threshold': 80.0,
    'ComparisonOperator': 'GreaterThanThreshold',
    'AlarmActions': ['arn:aws:sns:us-east-1:123456789012:Your-Alarm-Topic'],
    'OKActions': ['arn:aws:sns:us-east-1:123456789012:Your-Alarm-Topic']
}

# Create alarm for each instance
for instance_id in instance_ids:
    alarm_name = f"CPU-High-Alarm-{instance_id}"
    cloudwatch.put_metric_alarm(
        AlarmName=alarm_name,
        AlarmDescription=f"High CPU on instance {instance_id}",
        Dimensions=[{'Name': 'InstanceId', 'Value': instance_id}],
        **alarm_params
    )
    print(f"Created alarm: {alarm_name}")

Just install boto3 (pip install boto3), configure your AWS credentials, and run the script.

All these methods will save you from the hassle of creating 20 alarms manually. Pick the one that fits your workflow best!

内容的提问来源于stack exchange,提问作者Anup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:55:38