클라우드 배우기
CloudWatch Container Insight 설정 후, Whatap 및 slack 연동 + 알림 설정 본문
CloudWatch Container Insight 설치하여 모니터링
지정 역할 참고
https://hiheey.tistory.com/172
cloudwatch-agent 및 fluent bit 설치
kubectl create ns amazon-cloudwatch
환경 변수 설정
ClusterName=<클러스터명>
RegionName=<지역>
FluentBitHttpPort='2020'
FluentBitReadFromHead='Off'
[[ ${FluentBitReadFromHead} = 'On' ]] && FluentBitReadFromTail='Off'|| FluentBitReadFromTail='On'
[[ -z ${FluentBitHttpPort} ]] && FluentBitHttpServer='Off' || FluentBitHttpServer='On'
yaml 파일 다운로드
환경 변수 yaml 파일에 적용
sed -i 's/{{cluster_name}}/'${ClusterName}'/;s/{{region_name}}/'${RegionName}'/;s/{{http_server_toggle}}/"'${FluentBitHttpServer}'"/;s/{{http_server_port}}/"'${FluentBitHttpPort}'"/;s/{{read_from_head}}/"'${FluentBitReadFromHead}'"/;s/{{read_from_tail}}/"'${FluentBitReadFromTail}'"/' cwagent-fluent-bit-quickstart.yaml
yaml 파일 내 fluent-bit 의 affinity 부분 추가
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: eks.amazonaws.com/compute-type
operator: NotIn
values:
- fargate
나의 경우, cpu 가 충분하지 않아 하기와 같이 cloud-watch와 fluent-bit daemonset의 cpu를 축소했다.
cloudwatch > container insights 콘솔 확인
slack 으로 이동
kubectl get pod -o wide 로 버전 및 컨테이너 런타임 확인 후 yaml 다운로드
yaml 파일 다운로드
나의 경우, containerd가 런타임이지만 해당 yaml로는 실행이 되지 않아 Docker 로 다운받았더니 실행이 되었다.
하기와 같이 출력
slack.api 로 이동
create New App 클릭
From scratch 클릭하여 새로운 workspace를 생성 후, 선택할 것
새로운 워크스페이스 생성
생성한 워크스페이스 클릭 및 이름 기재
Incoming Webhooks 클릭
Actice incoming Webhooks 부분을 활성화시키면 Webhook URL 부분이 출력되고 Add New Webhook to Workspace 하여 생성한 워크스페이스를 연결한다. 그러면 하기와 같이 URL 값이 출력되고 해당 URL 복사
알림 설정을 위하여 SNS 생성
함수 생성
블루 프린트 사용하고 블루프린트 이름은 Send CloudWatch alarm notifications via SNS 로 선택
함수 생성 후, 개요 부분에서 함수 코드 변경이 가능하기 때문에 생성 후 바꿔줄 예정
SNS 트리거 부분에 이전에 생성한 주제 연결
환경 변수 부분에는 하기와 같이 slackChannel 과 hookUrl을 두 개를 넣어준다
slack 채널 부분 링크는 하기와 같이 복사 가능
생성된 화면
기존 생성되어 있던 함수 코드 변경
import boto3
import json
import logging
import os
from base64 import b64decode
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
# The base-64 encoded, encrypted key (CiphertextBlob) stored in the kmsEncryptedHookUrl environment variable
# ENCRYPTED_HOOK_URL = os.environ['kmsEncryptedHookUrl']
# The Slack channel to send a message to stored in the slackChannel environment variable
SLACK_CHANNEL = os.environ['slackChannel']
HOOK_URL = os.environ['hookUrl']
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("Event: " + str(event))
message = json.loads(event['Records'][0]['Sns']['Message'])
logger.info("Message: " + str(message))
alarm_name = message['AlarmName']
#old_state = message['OldStateValue']
new_state = message['NewStateValue']
reason = message['NewStateReason']
slack_message = {
'channel': SLACK_CHANNEL,
'text': "%s state is now %s: %s" % (alarm_name, new_state, reason)
}
req = Request(HOOK_URL, json.dumps(slack_message).encode('utf-8'))
try:
response = urlopen(req)
response.read()
logger.info("Message posted to %s", slack_message['channel'])
except HTTPError as e:
logger.error("Request failed: %d %s", e.code, e.reason)
except URLError as e:
logger.error("Server connection failed: %s", e.reason)
변경 후, Deploy 클릭
CloudWatch 지표 설정
나의 경우, EKS 를 Auto Scaling 으로 묶었기 때문에 Auto Scaling 그룹별 지표로 선택
EC2 > 해당되는 오토스케일링 그룹 선택
eks-node autoscaling 그룹의 CPU가 80% 경과 시, 슬랙으로 경보 알림
경보 알림 테스트
{
"Records": [
{
"EventSource": "aws:sns",
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:eu-west-1:000000000000:cloudwatch-alarms:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"Sns": {
"Type": "Notification",
"MessageId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"TopicArn": "arn:aws:sns:eu-west-1:000000000000:cloudwatch-alarms",
"Subject": "ALARM: \"Example alarm name\" in EU - Ireland",
"Message": "{\"AlarmName\":\"Example alarm name\",\"AlarmDescription\":\"Example alarm description.\",\"AWSAccountId\":\"000000000000\",\"NewStateValue\":\"ALARM\",\"NewStateReason\":\"Threshold Crossed: 1 datapoint (10.0) was greater than or equal to the threshold (1.0).\",\"StateChangeTime\":\"2017-01-12T16:30:42.236+0000\",\"Region\":\"EU - Ireland\",\"OldStateValue\":\"OK\",\"Trigger\":{\"MetricName\":\"DeliveryErrors\",\"Namespace\":\"ExampleNamespace\",\"Statistic\":\"SUM\",\"Unit\":null,\"Dimensions\":[],\"Period\":300,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":1.0}}",
"Timestamp": "2017-01-12T16:30:42.318Z",
"SignatureVersion": "1",
"Signature": "Cg==",
"SigningCertUrl": "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.pem",
"UnsubscribeUrl": "https://sns.eu-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-west-1:000000000000:cloudwatch-alarms:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"MessageAttributes": {}
}
}
]
}
'AWS' 카테고리의 다른 글
loadbalancer(gateway/+ 쿠키(stickness) (0) | 2024.01.22 |
---|---|
EKS Cloudwatch - Container Insight + Fluentd 설치 (0) | 2024.01.14 |
EKS EFS 클러스터 pod ContainerCreating 해결 (0) | 2024.01.09 |
EKF EFS 구성 (0) | 2024.01.07 |
EBS Volume 구성하여 mysql 설치 (1) | 2024.01.07 |