본문 바로가기
Server

AWS EC2- CloudWatch, Slack 연동 CPU, Memory 사용량 모니터링

by 오늘도 깨달았다 2022. 6. 20.
반응형

EC2 에 CloudWatch로 CPU, Memory 사용량 지표를 보고 일정 사용량을 넘어가면 우리 팀이 사용하는 협업 툴인 Slack으로 알림이 오게 구현할 일이 생겨 기록해둔다. 

 

EC2 instance는 가동중이라고 가정한다.

 

EC2 인스턴스의 시간이 한국 현재시간과 다르기 때문에 그 부분부터 맞춰줬다. 

 

//현재시간 확인 명령어
date

//현재시간이 한국 표준시간과 다르다면
rm /etc/localtime

//심볼릭 링크로 seoul 시간을 로컬타임에 넣기
ln -s /usr/share/zoneinfo/Asia/Seoul /etc/localtime

//다시 현재시간 확인
date

 

1. IAM Role 생성 

 

AWS console 검색창에 IAM 검색 후 클릭 

액세스 관리의 [역할] 클릭 후 [역할 만들기] 클릭 

 

[AWS 서비스] 의 [EC2] 클릭 후 다음 

 

필터에 "CloudWatchAgent" 검색 후 엔터 누르면 필터링된다. 

 

그 중 CloudWatchAgentServerPolicy 선택 후 다음 

자신이 알아볼 수 있는 이름으로 역할이름, 설명을 추가하고 [역할생성]


2. EC2 인스턴스에 방금 만든 IAM role 추가

EC2 인스턴스가 보이는 곳에서 우클릭 -> 보안 -> IAM 역할 수정 클릭 

IAM 역할 선택에서 방금 만든 IAM 역할 선택 후 [Update IAM role] 클릭

 


기본 모니터링에 메모리 사용량 체크는 들어가있지 않기 때문에 AWS 에이전트를 서버에 깔아서 마법사로 설정해줘야한다. 

 

3. EC2에 에이전트 다운로드와 마법사 실행

//sudo 권한으로 실행중이라고 가정, 에이전트 다운로드(Ubuntu 환경임, centos나 다른 OS이미지의 경우 경로가 달라짐)
cd /var
wget https://s3.ap-northeast-2.amazonaws.com/amazoncloudwatch-agent-ap-northeast-2/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb


dpkg -i -E ./amazon-cloudwatch-agent.deb

//마법사로 설정
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard


//쳐야할 내용들

================================================================
= Welcome to the Amazon CloudWatch Agent Configuration Manager =
=                                                              =
= CloudWatch Agent allows you to collect metrics and logs from =
= your host and send them to CloudWatch. Additional CloudWatch =
= charges may apply.                                           =
================================================================
On which OS are you planning to use the agent?
1. linux
2. windows
3. darwin
default choice: [1]:
1
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]:
1
Which user are you planning to run the agent?
1. root
2. cwagent
3. others
default choice: [1]:
2
Do you want to turn on StatsD daemon?
1. yes
2. no
default choice: [1]:
2
Do you want to monitor metrics from CollectD? WARNING: CollectD must be installed or the Agent will fail to start
1. yes
2. no
default choice: [1]:
2
Do you want to monitor any host metrics? e.g. CPU, memory, etc.
1. yes
2. no
default choice: [1]:
1
Do you want to monitor cpu metrics per core?
1. yes
2. no
default choice: [1]:
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]:
1
Do you want to aggregate ec2 dimensions (InstanceId)?
1. yes
2. no
default choice: [1]:
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]:
4
Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:
1
Current config as follows:
{
        "agent": {
                "metrics_collection_interval": 60,
                "run_as_user": "cwagent"
        },
        "metrics": {
                "aggregation_dimensions": [
                        [
                                "InstanceId"
                        ]
                ],
                "append_dimensions": {
                        "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
                        "ImageId": "${aws:ImageId}",
                        "InstanceId": "${aws:InstanceId}",
                        "InstanceType": "${aws:InstanceType}"
                },
                "metrics_collected": {
                        "disk": {
                                "measurement": [
                                        "used_percent"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        }
                }
        }
}
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]:
1
Do you have any existing CloudWatch Log Agent (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html) configuration file to import for migration?
1. yes
2. no
default choice: [2]:
2
Do you want to monitor any log files?
1. yes
2. no
default choice: [1]:
2
Saved config file to /opt/aws/amazon-cloudwatch-agent/bin/config.json successfully.
Current config as follows:
{
        "agent": {
                "metrics_collection_interval": 60,
                "run_as_user": "cwagent"
        },
        "metrics": {
                "aggregation_dimensions": [
                        [
                                "InstanceId"
                        ]
                ],
                "append_dimensions": {
                        "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
                        "ImageId": "${aws:ImageId}",
                        "InstanceId": "${aws:InstanceId}",
                        "InstanceType": "${aws:InstanceType}"
                },
                "metrics_collected": {
                        "disk": {
                                "measurement": [
                                        "used_percent"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        }
                }
        }
}
Please check the above content of the config.
The config file is also located at /opt/aws/amazon-cloudwatch-agent/bin/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]:
2
Program exits now.

설정을 완료했으면 설정파일 확인과 에이전트 데몬 실행

vi /opt/aws/amazon-cloudwatch-agent/bin/config.json

//존재한다면 나가도된다. 
:q!

 

cd /opt/aws/amazon-cloudwatch-agent/bin/

./amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 file://opt/aws/amazon-cloudwatch-agent/bin/config.json -s

 

에이전트 상태 확인  - Stopped가 정상임

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status
{
  "status": "stopped",
  "starttime": "",
  "configstatus": "configured",
  "cwoc_status": "stopped",
  "cwoc_starttime": "",
  "cwoc_configstatus": "not configured",
  "version": "1.247352.0b251908"
}

 

에이전트 시작하기

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a start

에이전트 데몬 확인 

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status


{
  "status": "running",
  "starttime": "2022-06-20T07:03:55+00:00",
  "configstatus": "configured",
  "cwoc_status": "stopped",
  "cwoc_starttime": "",
  "cwoc_configstatus": "not configured",
  "version": "1.247352.0b251908"
}

 

ps -ef |grep amazon-cloudwatch-agent

 

에러가 없는지 확인 

cd /opt/aws/amazon-cloudwatch-agent/logs

vi amazon-cloudwatch-agent.log

 

CloudWatch에서 메모리 모니터링 되는지 확인 

CloudWatch -> 지표 -> CWAgent -> ImageId, InstanceId, InstanceType

오른쪽 위에 메모리 사용량이 표시된걸 볼 수 있다.


방금 만든 지표와 CPU 사용량, 메모리 사용량 Slack 연동 

 

1. SNS 토픽 생성 

 

Amazon SNS -> 주제 -> 주제 생성

 

표준과 이름을 만든 후 주제생성 

 

2. AWS chatbot 서비스로 이동 후 새 클라이언트 구성 클릭 

슬랙 선택후 구성

 

본인의 워크스페이스를 선택 후 허용

생성한 클라이언트로 들어가서 [새 채널 구성] 클릭

 

구성 이름 : 본인이 알아볼 수 있는 이름 

퍼블릭 채널 이름 : 알림을 받길 원하는 채널 선택 

역할이름은 본인이 알아볼 수 있는 이름

 

채널 가드레일 정책 : AWS-Chatbot-NotificationsOnly-Policy 로 되어있는 부분을 선택하시오

 

그 후 생성 

 

3. CloudWatch 경보 설정 

CloudWatch 콘솔 접속 후 경보 생성 클릭 

 

지표에서 아까 봤던 것중에 원하는 지표 클릭 (메모리는 CWAgent, CPU는 EC2 에 있음 )

 

CPU로 예시를 들면 EC2 -> 인스턴스별 지표 

CPUUtilization 선택 후 지표선택 

 

임계값 정의 (80% 라면 80 ) 후 다음 클릭

 

다음으로 알림 전송 칸에 아까 만든 slack 알람이 있음 -> 선택 후 다음

 

 

이름 및 설명 원하는 것으로 설정  후 다음 

 

정보들이 맞는지 확인 후 경보생성 을 누르면 slack로 알람을 받을 수 있습니다. 

작업이 활성화됨 떠있어야합니다 

반응형

댓글