본문 바로가기
AWS

[CloudWatch] CloudWatch 경보 설정하기 - 2

by yonikim 2021. 6. 17.
728x90

1. AWS EC2 인스턴스에 CloudWatch Agent 설치하기

2. Slack에 알람 보내는 AWS SNS & AWS Lambda 함수 생성하기

3. AWS CloudeWatch 설정하기

 

 


AWS SNS 생성하기


 

1. AWS Console 로그인 후 Simple Notification Service 에 들어간다.

 

2. [주제 생성] 버튼을 클릭한다.

 

3. 유형은 [표준] 을 선택한다.

 

 


AWS Lambda 함수 생성하기


 

1. Lambda 함수 생성하기

 

▷ index.js

const axios = require('axios')

exports.handler = async (event) => {
  console.log(JSON.stringify(event))

  const SLACK_ENDPOINT = `${SLACK_WEBHOOK_URL}`
  const msg = JSON.parse(event['Records'][0]['Sns']['Message'])

  let issue, issueOn

  const NewStateReason = msg['NewStateReason']
  const Dimensions = msg['Trigger']['Dimensions']
  const MetricName = msg['Trigger']['MetricName']
  const Threshold = msg['Trigger']['Threshold']

  const reason = /.*datapoints \[(.*)\].*/g.exec(NewStateReason)[1]

  if (MetricName == 'DatabaseConnections') {
    issue = 'DB 연결 수 과도'
    issueOn = `${Threshold} 초과 [ ${reason} ]`
  } else if (MetricName == 'FreeableMemory') {
    const mb = Threshold / 1000000
    issue = '사용 가능한 메모리 공간 부족'
    issueOn = `${mb} MB 보다 부족 [ ${reason} ]`
  } else if (MetricName == 'CPUUtilization') {
    issue = 'CPU 사용량 과도'
    issueOn = `CPU 사용량 ${Threshold} % 초과 [ ${reason} ]`
  } else if (MetricName == 'disk_used_percent') {
    issue = '디스크 용량이 가득 참'
    issueOn = `디스크 용량 ${Threshold} % 초과 [ ${reason} ]`
  } else {
    issue = MetricName
    issueOn = `${Threshold} 초과`
  }
  const InstanceId = Dimensions.filter((Dimension) => Dimension.name == 'InstanceId')[0]
  const DBInstanceIdentifier = Dimensions.filter((Dimension) => Dimension.name == 'DBInstanceIdentifier')[0]

  let instanceId, rdsName

  if (InstanceId) {
    instanceId = InstanceId.value
  }
  if (DBInstanceIdentifier) {
    rdsName = DBInstanceIdentifier.value
  }
  const name = rdsName ? rdsName : instanceId

  const message = {
    blocks: [
      {
        type: 'header',
        text: {
          type: 'plain_text',
          text: '[' + name + '] 인프라 위험 탐지 :zap:',
          emoji: true,
        },
      },
      {
        type: 'section',
        text: {
          type: 'mrkdwn',
          text: '> *알림 |* ' + name + ' / ' + issue + '\n> *기준 |* ' + issueOn,
        },
      },
    ],
  }

  try {
    await axios.post(SLACK_ENDPOINT, message)
    return {
      status: 200,
      body: JSON.stringify(
        {
          message: 'Successfully ended',
          input: event,
        },
        null,
        2
      ),
    }
  } catch (err) {
    return {
      statusCode: 500,
      body: 'Error',
    }
  }
}

 

2. [구성] 탭 클릭 > [트리거] 탭 클릭 > [트리거 추가] 버튼을 클릭한다.

 

3. 위에서 만든 SNS 주제와 연결한다.

728x90