[AWS] EventBridge: batch 실패 알림 띄우기

AWS Batch로 배치 프로세스를 돌리다보니, 예측할수 없는 다양한 사유로 프로세스가 터질 일이 많아서 이에 대한 알림 기능을 도입할 필요를 느꼈다.

Batch 실패시 -> 슬랙으로 알림을 띄워주는 식으로 말이다.

이벤트브릿지를 이용하면 이에 대한 처리를 어렵지 않게 할 수 있다.

먼저 알림을 보낼 로직을 구현할, 람다함수를 작성한다.

로직은 이렇다.

const axios = require('axios');

// 슬랙 웹훅 링크
const SLACK_URL = `https://hooks.slack.com/services/.../.../...`;

exports.handler = async (event) => {
    const detail = event.detail;

    const jobName = detail.jobName;
    const jobQueue = detail.jobQueue;
    const status = detail.status;
    const reason = detail.statusReason;

    const text = `I am Groot!
<!here>

BATCH 실패 알림
\`\`\`
${jobQueue} -> ${jobName}
STATUS: ${status}
REASON: ${reason}
\`\`\`
`

   await axios.post(SLACK_URL, {
		username: 'I am Groot',
		text,
		channel: 'C03A0CG1BQD',
	});

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

실패한 프로세스 큐, 프로세스 이름, 실패사유 정도만 출력해주도록 간단하게 구현했다.

그리고 이벤트브릿지 콘솔로 이동해 새 "규칙"을 생성한다.
이 기능을 이용하면 aws 내 수많은 변동사항에 대해서 트리거를 걸 수 있다.
우리의 경우엔 Batch의 상태가 "FAILED"로 이동될때를 조건으로 걸 수 있겠다.

먼저 규칙의 이름을 정해주고

2단계에서 스크롤을 좀 내려서

이벤트 패턴을 다음과 같이 직접 작성해준다.

복붙해서 넣으면 된다.

{
  "detail-type": [
    "Batch Job State Change"
  ],
  "source": [
    "aws.batch"
  ],
  "detail": {
    "status": [
      "FAILED"
    ]
  }
}

3단계에선 어떤 서비스를 호출시킬지를 정한다.

방금 만든 람다를 등록해주면 된다.


다 만들어주고,

실패하는 프로세스를 하나 띄워보면

이렇게 잘 날라올 것이다.

다른 코드 예제

const axios = require('axios');

// 슬랙 웹훅 링크
const SLACK_URL = `https://hooks.slack.com/services/...`;

exports.handler = async (event) => {
    console.log(event);
    const detail = event.detail;

    const jobName = detail.jobDefinition?.split('/')?.[1];
    const jobQueue = detail.jobQueue?.split('/')?.[1];
    const status = detail.status;
    const reason = detail.statusReason;

    const jobId = detail.jobId;

    const link = `https://ap-northeast-2.console.aws.amazon.com/batch/home?region=ap-northeast-2#jobs/fargate/detail/${jobId}`

    const text = `Oops!
<!here>

BATCH 실패 알림
\`\`\`
${jobQueue} -> ${jobName}
상태: ${status}
사유: ${reason}
콘솔 이동: ${link}
\`\`\`
`

   await axios.post(SLACK_URL, {
		username: 'batchman',
		text,
		channel: '...',
	});

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};