Giới Thiệu về CloudWatch Alarms
CloudWatch Alarms là một thành phần quan trọng của dịch vụ giám sát Amazon CloudWatch, cho phép bạn tự động theo dõi các metrics và kích hoạt các hành động dựa trên ngưỡng xác định trước. Đối với kỳ thi AWS Certified Developer – Associate (DVA-C02), hiểu rõ về CloudWatch Alarms là điều cần thiết vì đây là một phần thiết yếu trong việc xây dựng các ứng dụng đáng tin cậy, tự phục hồi trên AWS.
Các Khái Niệm Cơ Bản
1. Định Nghĩa và Cách Thức Hoạt Động
CloudWatch Alarms theo dõi một metric cụ thể trong một khoảng thời gian xác định và thực hiện các hành động dựa trên giá trị của metric đó so với một ngưỡng đã được thiết lập. Mỗi alarm có ba trạng thái chính:
- OK: Metric nằm trong ngưỡng định nghĩa là bình thường
- ALARM: Metric vượt quá ngưỡng đã thiết lập
- INSUFFICIENT_DATA: Không đủ dữ liệu để xác định trạng thái
2. Các Thành Phần Chính của Alarm
- Metric: Số liệu được giám sát (như CPU Utilization, Error Count)
- Threshold: Giá trị ngưỡng kích hoạt cảnh báo
- Period: Khoảng thời gian đánh giá metric (như 60 giây, 5 phút)
- Evaluation Periods: Số lượng period liên tiếp mà metric phải vượt ngưỡng
- Datapoints to Alarm: Số lượng datapoints trong evaluation periods cần vượt ngưỡng
- Statistic: Phương pháp thống kê áp dụng (Average, Sum, Minimum, Maximum, Sample Count, percentiles)
- Comparison Operator: Toán tử so sánh (Greater/Less Than, Greater/Less Than or Equal)
Loại CloudWatch Alarms
1. Metric Alarms
Đây là loại alarm phổ biến nhất, theo dõi các CloudWatch metrics và kích hoạt hành động khi metrics đạt hoặc vượt ngưỡng.
{
"AlarmName": "CPUUtilizationAlarm",
"AlarmDescription": "Alarm when CPU exceeds 70%",
"ActionsEnabled": true,
"OKActions": [],
"AlarmActions": ["arn:aws:sns:us-east-1:123456789012:my-topic"],
"InsufficientDataActions": [],
"MetricName": "CPUUtilization",
"Namespace": "AWS/EC2",
"Statistic": "Average",
"Dimensions": [
{
"Name": "InstanceId",
"Value": "i-12345678"
}
],
"Period": 300,
"EvaluationPeriods": 1,
"Threshold": 70,
"ComparisonOperator": "GreaterThanThreshold"
}
2. Composite Alarms
Composite Alarms kết hợp nhiều alarm đơn lẻ bằng các quy tắc logic (AND, OR, NOT) để giảm thiểu cảnh báo sai và giúp xử lý kịch bản phức tạp hơn.
{
"AlarmName": "CompositeServerAlarm",
"AlarmRule": "ALARM(CPUUtilizationAlarm) AND ALARM(MemoryUtilizationAlarm)",
"AlarmDescription": "Alarm when both CPU and Memory are high",
"ActionsEnabled": true,
"AlarmActions": ["arn:aws:sns:us-east-1:123456789012:critical-alerts"]
}
3. Anomaly Detection Alarms
Sử dụng machine learning để phát hiện các hành vi bất thường trong metrics, thay vì dựa vào ngưỡng tĩnh.
{
"AlarmName": "AnomalyDetectionAlarm",
"MetricName": "RequestCount",
"Namespace": "AWS/ApiGateway",
"Statistic": "Sum",
"Period": 300,
"EvaluationPeriods": 1,
"ThresholdMetricId": "ad1",
"ComparisonOperator": "GreaterThanUpperThreshold",
"Threshold": 0,
"TreatMissingData": "missing",
"AlarmDescription": "Anomaly detection for API requests",
"AlarmActions": ["arn:aws:sns:us-east-1:123456789012:alerts"],
"Dimensions": [
{
"Name": "ApiName",
"Value": "MyAPI"
}
],
"AnomalyDetectorMetricStat": {
"Metric": {
"MetricName": "RequestCount",
"Namespace": "AWS/ApiGateway"
},
"Period": 300,
"Stat": "Sum"
}
}
Các Hành Động của CloudWatch Alarms
1. Amazon SNS Notifications
Gửi thông báo tới các đối tượng đăng ký thông qua Amazon SNS khi alarm chuyển trạng thái.
import boto3
# Tạo SNS topic
sns_client = boto3.client('sns')
response = sns_client.create_topic(Name='alarm-notifications')
topic_arn = response['TopicArn']
# Đăng ký email
sns_client.subscribe(
TopicArn=topic_arn,
Protocol='email',
Endpoint='admin@example.com'
)
# Tạo alarm kết nối với SNS
cloudwatch = boto3.client('cloudwatch')
cloudwatch.put_metric_alarm(
AlarmName='HighCPUAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=1,
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Period=300,
Statistic='Average',
Threshold=70.0,
AlarmDescription='Alarm when CPU exceeds 70%',
AlarmActions=[topic_arn],
Dimensions=[
{
'Name': 'InstanceId',
'Value': 'i-12345678'
},
],
)
2. Auto Scaling Actions
Kích hoạt Auto Scaling để thay đổi số lượng EC2 instances dựa trên trạng thái của alarm.
# Tạo alarm kích hoạt auto scaling
cloudwatch.put_metric_alarm(
AlarmName='ScaleUpAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=2,
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Period=300,
Statistic='Average',
Threshold=75.0,
AlarmDescription='Alarm when CPU exceeds 75%',
AlarmActions=[
f'arn:aws:autoscaling:us-east-1:123456789012:scalingPolicy:policy-id:autoScalingGroupName/my-asg:policyName/scale-out'
],
Dimensions=[
{
'Name': 'AutoScalingGroupName',
'Value': 'my-asg'
},
],
)
3. EC2 Actions
Thực hiện các hành động trên EC2 instances như Stop, Terminate hoặc Reboot.
# Tạo alarm tự động reboot EC2 instance
cloudwatch.put_metric_alarm(
AlarmName='InstanceHealthAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=3,
MetricName='StatusCheckFailed',
Namespace='AWS/EC2',
Period=300,
Statistic='Maximum',
Threshold=0,
AlarmDescription='Alarm when instance health check fails',
AlarmActions=[
f'arn:aws:automate:us-east-1:ec2:reboot'
],
Dimensions=[
{
'Name': 'InstanceId',
'Value': 'i-12345678'
},
],
)
4. Lambda Functions
Kích hoạt Lambda function để thực hiện logic xử lý phức tạp.
# Tạo alarm gọi Lambda function
cloudwatch.put_metric_alarm(
AlarmName='DatabaseErrorAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=1,
MetricName='Errors',
Namespace='Custom/Database',
Period=60,
Statistic='Sum',
Threshold=5,
AlarmDescription='Alarm when database errors occur',
AlarmActions=[
f'arn:aws:sns:us-east-1:123456789012:invoke-lambda'
],
Dimensions=[
{
'Name': 'DatabaseName',
'Value': 'production-db'
},
],
)
Xử Lý Dữ Liệu Thiếu trong CloudWatch Alarms
CloudWatch Alarms cung cấp nhiều tùy chọn để xử lý trường hợp không có đủ dữ liệu để đánh giá:
- breaching: Coi dữ liệu thiếu là vi phạm ngưỡng
- notBreaching: Coi dữ liệu thiếu là không vi phạm ngưỡng
- ignore: Duy trì trạng thái alarm hiện tại
- missing: Chuyển sang trạng thái INSUFFICIENT_DATA
# Cấu hình xử lý dữ liệu thiếu
cloudwatch.put_metric_alarm(
# ...các thông số khác...
TreatMissingData='breaching',
# ...
)
CloudWatch Alarms với High-Resolution Metrics
CloudWatch Alarms cũng hỗ trợ làm việc với High-Resolution Metrics (có độ phân giải 1 giây):
# Tạo alarm cho high-resolution metric
cloudwatch.put_metric_alarm(
AlarmName='APILatencyAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=3,
MetricName='Latency',
Namespace='Custom/API',
Period=10, # 10 giây, thay vì 60 giây
Statistic='Average',
Threshold=100,
AlarmDescription='Alarm when API latency exceeds 100ms',
AlarmActions=[topic_arn],
)
Các Trường Hợp Sử Dụng Thực Tế
1. Giám Sát Hiệu Suất Ứng Dụng
# Giám sát thời gian phản hồi API
cloudwatch.put_metric_alarm(
AlarmName='APIResponseTimeAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=2,
MetricName='ResponseTime',
Namespace='AWS/ApiGateway',
Period=60,
Statistic='Average',
Threshold=200.0, # 200ms
AlarmDescription='Alarm when API response time is too high',
AlarmActions=[topic_arn],
Dimensions=[
{
'Name': 'ApiName',
'Value': 'customer-api'
},
],
)
2. Giám Sát Chi Phí
# Giám sát chi phí ước tính vượt ngưỡng
cloudwatch.put_metric_alarm(
AlarmName='BillingAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=1,
MetricName='EstimatedCharges',
Namespace='AWS/Billing',
Period=21600, # 6 giờ
Statistic='Maximum',
Threshold=100.0, # 100 USD
AlarmDescription='Alarm when AWS bill exceeds $100',
AlarmActions=[topic_arn],
Dimensions=[
{
'Name': 'Currency',
'Value': 'USD'
},
],
)
3. Giám Sát Bảo Mật
# Phát hiện các login thất bại bất thường
cloudwatch.put_metric_alarm(
AlarmName='FailedLoginAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=1,
MetricName='FailedLoginAttempts',
Namespace='Custom/Security',
Period=300,
Statistic='Sum',
Threshold=5,
AlarmDescription='Alarm when multiple failed logins occur',
AlarmActions=[topic_arn],
)
4. Giám Sát Tình Trạng Hệ Thống
# Giám sát trạng thái hệ thống
cloudwatch.put_metric_alarm(
AlarmName='SystemStatusAlarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=2,
MetricName='StatusCheckFailed_System',
Namespace='AWS/EC2',
Period=300,
Statistic='Maximum',
Threshold=0,
AlarmDescription='Alarm when system status check fails',
AlarmActions=[topic_arn],
Dimensions=[
{
'Name': 'InstanceId',
'Value': 'i-12345678'
},
],
)
CloudWatch Alarms và AWS EventBridge (CloudWatch Events)
CloudWatch Alarms có thể kết hợp với AWS EventBridge để tạo ra các luồng xử lý phức tạp:
# Tạo EventBridge rule cho alarm state change
events_client = boto3.client('events')
response = events_client.put_rule(
Name='AlarmStateChangeRule',
EventPattern='''{
"source": ["aws.cloudwatch"],
"detail-type": ["CloudWatch Alarm State Change"],
"detail": {
"alarmName": ["CPUUtilizationAlarm"],
"state": {
"value": ["ALARM"]
}
}
}''',
State='ENABLED'
)
# Thêm Lambda function làm target
events_client.put_targets(
Rule='AlarmStateChangeRule',
Targets=[
{
'Id': '1',
'Arn': 'arn:aws:lambda:us-east-1:123456789012:function:handle-alarm'
}
]
)
Best Practices
- Đặt ngưỡng phù hợp: Dựa trên dữ liệu lịch sử và benchmark
- Sử dụng Composite Alarms: Giảm nhiễu và cảnh báo sai
- Phân loại mức độ nghiêm trọng: Phân biệt cảnh báo thông thường và khẩn cấp
- Thiết lập alarm description rõ ràng: Mô tả vấn đề và hành động cần thực hiện
- Sử dụng Anomaly Detection: Cho hệ thống có mẫu sử dụng thay đổi nhiều
- Cấu hình TreatMissingData hợp lý: Dựa trên đặc điểm của metric
- Xem xét số period và datapoints: Tránh cảnh báo sai do biến động tạm thời
Một Số Điểm Cần Nhớ Cho Kỳ Thi DVA-C02
- Thời gian đánh giá: Mặc định, alarm đánh giá dựa trên các metric trong 5 phút gần nhất
- Trạng thái alarm: ALARM, OK, INSUFFICIENT_DATA
- Các thuộc tính cơ bản: MetricName, Namespace, Statistic, Period, EvaluationPeriods, Threshold
- Các loại hành động: SNS, AutoScaling, EC2 Action, Lambda
- Metric Math: Cho phép tạo alarm dựa trên biểu thức toán học giữa nhiều metrics
- M out of N: Cấu hình alarm để kích hoạt khi M trong N periods vượt ngưỡng
Tạo CloudWatch Alarms thông qua AWS CLI
# Tạo alarm đơn giản
aws cloudwatch put-metric-alarm \
--alarm-name high-cpu-alarm \
--alarm-description "Alarm when CPU exceeds 70%" \
--metric-name CPUUtilization \
--namespace AWS/EC2 \
--statistic Average \
--period 300 \
--threshold 70 \
--comparison-operator GreaterThanThreshold \
--dimensions Name=InstanceId,Value=i-12345678 \
--evaluation-periods 1 \
--alarm-actions arn:aws:sns:region:account-id:my-topic
# Tạo composite alarm
aws cloudwatch put-composite-alarm \
--alarm-name composite-system-alarm \
--alarm-rule "(ALARM(high-cpu-alarm) OR ALARM(low-memory-alarm)) AND ALARM(high-disk-usage-alarm)" \
--alarm-actions arn:aws:sns:region:account-id:critical-alerts
CloudWatch Alarms với CloudFormation
Resources:
HighCPUAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: HighCPUAlarm
AlarmDescription: Alarm when CPU exceeds 70%
MetricName: CPUUtilization
Namespace: AWS/EC2
Statistic: Average
Period: 300
EvaluationPeriods: 1
Threshold: 70
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Dimensions:
- Name: InstanceId
Value: !Ref MyEC2Instance
AlarmActions:
- !Ref AlarmNotificationTopic
AlarmNotificationTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: AlarmNotifications
Subscription:
- Endpoint: admin@example.com
Protocol: email
Giới Hạn và Bảo Mật
- Số lượng alarm: Tối đa 10 alarms trên mỗi metric
- Định danh alarms: Dùng IAM policies để hạn chế quyền tạo và quản lý alarms
- Encryption: SNS topics có thể được mã hóa để bảo vệ thông báo cảnh báo
- Access logging: Theo dõi các hành động liên quan đến alarms qua CloudTrail
Kết Luận
CloudWatch Alarms là một công cụ thiết yếu cho việc giám sát, cảnh báo và tự động hóa phản ứng với các sự kiện trong môi trường AWS. Việc hiểu rõ cách cấu hình và sử dụng CloudWatch Alarms không chỉ giúp bạn vượt qua kỳ thi AWS DVA-C02 mà còn là kỹ năng quan trọng để xây dựng các hệ thống đáng tin cậy và tự động hóa trên AWS.
Khi ôn thi, hãy tập trung vào các thành phần cơ bản của CloudWatch Alarms, các loại alarm, cách xử lý dữ liệu thiếu, và các hành động có thể được kích hoạt. Đồng thời, hãy thực hành tạo và quản lý alarms thông qua Console, CLI, và CloudFormation để có kinh nghiệm thực tế.