Windows에 CloudWatch Agent를 설정하고, CloudFormation으로 메모리, 디스크 사용률을 이메일로 통지하는 CloudWatch Alarm을 생성해 보기

Windows에 CloudWatch Agent를 설정하고, CloudFormation으로 메모리, 디스크 사용률을 이메일로 통지하는 Cloudwatch Alarm을 생성해 보는 과정을 정리해 봤습니다.
2022.08.21

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

안녕하세요 클래스메소드 김재욱(Kim Jaewook) 입니다. 이번에는 Windows에 CloudWatch Agent를 설정하고, CloudFormation으로 메모리, 디스크 사용률을 이메일로 통지하는 Cloudwatch Alarm을 생성해 보는 과정을 정리해 봤습니다.

사전에 EC2 Instance와 IAM Role, SNS Topic이 설정되어 있다고 가정한 상태로 작업을 진행합니다.

EC2 Instance에는 다음과 같은 IAM Role이 설정되어 있습니다.

  • AmazonSSMManagedInstanceCore
  • CloudWatchAgentAdminPolicy

CloudWatch Agent 설정

CloudWatch Agent 설정 파일을 다운로드 하기 위해 Run Command에서 AWS-ConfigureAWSPackage를 이용합니다.

Name에는 AmazonCloudWatchAgent를 입력하고, 타겟 EC2 Instance를 선택한 다음 Run Command를 실행합니다.

Run Command 실행 후, 조금 기다려 보면 명령 상태가 성공으로 바뀌는 것을 확인할 수 있습니다.

cd "C:\Program Files\Amazon\AmazonCloudWatchAgent"
.\amazon-cloudwatch-agent-config-wizard.exe

이제 EC2 Instance에서 다음 명령을 입력합니다. (IAM Role에 SSM으로 접속할 수 있는 권한을 설정했기 때문에, 콘솔환경에서 바로 SSM으로 접속해서 실행해도 상관없습니다.)


=============================================================
= Welcome to the AWS CloudWatch Agent Configuration Manager =
=============================================================
On which OS are you planning to use the agent?
1. linux
2. windows
default choice: [2]:

Trying to fetch the default region based on ec2 metadata...
Are you using EC2 or On-Premises hosts?
1. EC2
2. On-Premises
default choice: [1]:

Do you want to turn on StatsD daemon?
1. yes
2. no
default choice: [1]:


Which port do you want StatsD daemon to listen to?
default choice: [8125]

What is the collect interval for StatsD daemon?
1. 10s
2. 30s
3. 60s
default choice: [1]:

What is the aggregation interval for metrics collected by StatsD daemon?
1. Do not aggregate
2. 10s
3. 30s
4. 60s
default choice: [4]:

Do you have any existing CloudWatch Log Agent configuration file to import for migration?
1. yes
2. no
default choice: [2]:

Do you want to monitor any host metrics? e.g. CPU, memory, etc.
1. yes
2. no
default choice: [1]:

Do you want to monitor cpu metrics per core?
1. yes
2. no
default choice: [1]:

Do you want to add ec2 dimensions (ImageId, InstanceId, InstanceType, AutoScalingGroupName) into all of your metrics if the info is available?
1. yes
2. no
default choice: [1]:

Do you want to aggregate ec2 dimensions (InstanceId)?
1. yes
2. no
default choice: [1]:

Would you like to collect your metrics at high resolution (sub-minute resolution)? This enables sub-minute resolution for all metrics, but you can customize for specific metrics in the output json file.
1. 1s
2. 10s
3. 30s
4. 60s
default choice: [4]:

Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:
2

Are you satisfied with the above config? Note: it can be manually customized after the wizard completes to add additional items.
1. yes
2. no
default choice: [1]:

Do you want to monitor any customized log files?
1. yes
2. no
default choice: [1]:
2

Do you want to monitor any Windows event log?
1. yes
2. no
default choice: [1]:
2

Please check the above content of the config.
The config file is also located at config.json.
Edit it manually if needed.
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:

What parameter store name do you want to use to store your config? (Use 'AmazonCloudWatch-' prefix if you use our managed AWS policy)
default choice: [AmazonCloudWatch-windows]
AmazonCloudWatch-test-cloudwatchagent

Trying to fetch the default region based on ec2 metadata...
Which region do you want to store the config in the parameter store?
default choice: [ap-northeast-1]

Which AWS credential should be used to send json config to parameter store?
1. ASIAYGKV54QYWOZRWI3G(From SDK)
2. Other
default choice: [1]:

입력한 숫자가 없을 경우 디폴트로 설정 했습니다.


Do you want to add ec2 dimensions (ImageId, InstanceId, InstanceType, AutoScalingGroupName) into all of your metrics if the info is available?
1. yes
2. no
default choice: [1]:

여기서 몇 가지 집고 넘어가자면, 상기 질문에 대해서 yes, no를 입력했을 시 CloudWatch Agent에 나타나는 지표가 조금 달라집니다.


Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:
2

이어서 다음 지표를 선택하는 부분입니다.

Basic, Standard 등등 선택에 따라 지표가 달라지게 됩니다.

자세한 사항은 아래 링크를 참고해 주세요.


Please check the above content of the config.
The config file is also located at config.json.
Edit it manually if needed.
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:

What parameter store name do you want to use to store your config? (Use 'AmazonCloudWatch-' prefix if you use our managed AWS policy)
default choice: [AmazonCloudWatch-windows]
AmazonCloudWatch-test-cloudwatchagent

Trying to fetch the default region based on ec2 metadata...
Which region do you want to store the config in the parameter store?
default choice: [ap-northeast-1]

Which AWS credential should be used to send json config to parameter store?
1. ASIAYGKV54QYWOZRWI3G(From SDK)
2. Other
default choice: [1]:

마지막으로 Parameter Store에 CloudWatch Agent 설정값을 저장하는 부분입니다.

설정값의 이름은 반드시「AmazonCloudWatch-」로 시작할 필요가 있습니다.

Parameter Store로 가보면 설정한 값이 생성된 것을 확인할 수 있습니다.

이어서 CloudWatch Agent를 실행하기 위해 Run Command에서 AmazonCloudWatch-ManageAgent를 실행합니다.

이어서 Optional Configuration Location에 Parameter Store에 저장한 CloudWatch Agent 설정 값을 저장하고 Run Command를 실행합니다.

CloudWatch에서「모든 지표」로 들어가 보면「CWAgent」가 생성된 것을 확인할 수 있습니다.

지표로 들어가서 메모리 사용률과 디스크 사용률 지표가 있는지 확인합니다.

그 외 다른 지표에 관한 내용은 아래 링크를 참고해 주세요.

CloudFormation으로 CloudWatch Alarm 생성

AWSTemplateFormatVersion: "2010-09-09"
Description: Create CloudWatch Alarms

Parameters:
# Input Parameters
EC2InstanceId:
Description: "EC2 Instance id of test"
Type: AWS::EC2::Instance::Id
SNSTopicName:
Description: "SNS Topic Name of sns arn"
Type: String
Default: arn:aws:sns:ap-northeast-1

Resources:
# Create CloudWatch Alarms
CPUUtilizationAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmActions:
- !Ref SNSTopicName
AlarmName: CPUUtilization
MetricName: CPUUtilization
Namespace: AWS/EC2
Statistic: Average
Period: 300
EvaluationPeriods: 1
Threshold: 80
OKActions:
- !Ref SNSTopicName
ComparisonOperator: GreaterThanOrEqualToThreshold
Dimensions:
- Name: InstanceId
Value: !Ref EC2InstanceId
StatusCheckAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmActions:
- !Ref SNSTopicName
AlarmName: StatusCheckAlarm
MetricName: StatusCheckFailed
Namespace: AWS/EC2
Statistic: Average
Period: 60
EvaluationPeriods: 1
Threshold: 0
OKActions:
- !Ref SNSTopicName
ComparisonOperator: GreaterThanThreshold
Dimensions:
- Name: InstanceId
Value: !Ref EC2InstanceId
MemoryAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmActions:
- !Ref SNSTopicName
AlarmName: MemoryAlarm
MetricName: Memory % Committed Bytes In Use
Namespace: AWS/EC2
Statistic: Average
Period: 300
EvaluationPeriods: 1
Threshold: 80
OKActions:
- !Ref SNSTopicName
ComparisonOperator: GreaterThanOrEqualToThreshold
Dimensions:
- Name: InstanceId
Value: !Ref EC2InstanceId
DiskAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmActions:
- !Ref SNSTopicName
AlarmName: DiskAlarm
MetricName: LogicalDisk % Free Space
Namespace: AWS/EC2
Statistic: Average
Period: 300
EvaluationPeriods: 1
Threshold: 80
OKActions:
- !Ref SNSTopicName
ComparisonOperator: GreaterThanOrEqualToThreshold
Dimensions:
- Name: InstanceId
Value: !Ref EC2InstanceId

CloudFormation Stack을 생성합니다.

Instance ID, SNS Topic arn을 입력하고 Stack 생성을 끝마칩니다.

CloudWatch로 들어가서 확인해 보면, CloudFormation으로도 CloudWatch Agent에서 설정한 메모리 사용률, 디스크 사용률을 CloudWatch Alarm으로 만들 수 있는 것을 확인할 수 있습니다.

본 블로그 게시글을 보시고 문의 사항이 있으신 분들은 클래스메소드코리아 (info@classmethod.kr)로 연락 주시면 빠른 시일 내 담당자가 회신 드릴 수 있도록 하겠습니다 !