Skip to main content

4️⃣ Eventbridge 기반 DB 스캐닝으로 오래된 이슈 확인하기

arc.png

✅ 실습 전 us-west-2 리전이 맞는지 확인해주세요!

Lambda 생성

람다 함수를 하나 더 생성합니다. 생성된지 '10분' 이상된 Issue가 '1개' 이상이면 해당 Issue URL과 함께 경고 알림 문자 메시지 전송하는 로직을 담은 람다 함수입니다.

arc.png

코드 창에 다음 코드를 붙여 넣고 Deploy 버튼을 눌러줍니다.

아래의 코드는 다음과 같은 로직을 갖습니다. 작은 따옴표로 표기된 시간은 코드에서 변경이 가능합니다.

  1. EventBridge가 '5분' or '3분'마다 CheckOldIssues Lambda를 invoke (실습이므로 빠른 테스트를 위해 짧게 설정하는 것을 추천드립니다.)
  2. CheckOldIssues Lambda에서는 깃허브에서 생성된 issue 및 PR 데이터를 담은 DynamoDB에 접근
    1. Created time과 현재 시간 - '10분' 을 비교
    2. Created time <= 현재 시간 - '10분' 이라면 Old Issues +1
    3. Old Issues >= 1 이라면 SNS publish
import json
import boto3
from datetime import datetime, timezone

dynamodb = boto3.resource('dynamodb')
sns_client = boto3.client('sns', region_name='us-west-2')
phone_number = "+82010xxxxxxxx"
table = dynamodb.Table('GitHubEvent')

def lambda_handler(event, context):
try:
now = int(datetime.now(timezone.utc).timestamp()) # 현재 시간 (UTC, Unix Timestamp)
ten_minutes_ago = now - 600 # 10분 전 시간

# 10분 이상 지난 이슈 조회
response = table.scan(
FilterExpression="created_timestamp <= :timestamp AND #act = :open AND #evt = :issues",
ExpressionAttributeValues={":timestamp": ten_minutes_ago, ":open" : "opened", ":issues" : "issues"},
ExpressionAttributeNames={"#act": "action", "#evt": "event_type"},
)
response2 = table.scan(
ProjectionExpression="attribute1, attribute2, attribute3",
)
print("datetime.now(timezone.utc):",now)
print("ten_minutes_ago:",ten_minutes_ago)
print(response2)

old_issues = response.get('Items', [])
print(old_issues)
issue_count = len(old_issues)
print(f"Found {issue_count} old issues (10분 이상 된 이슈)")

# 1개 이상이면 SMS 전송
if issue_count >= 1:
message = f":warning: {issue_count} old issues found! Check them here:\n"
for issue in old_issues[:3]: # 최대 3개 링크 포함
message += f"- {issue['title']}: {issue['url']}\n"
# SNS로 메시지 전송
sns_client.publish(
PhoneNumber=phone_number,
Message=message,
)

print("SNS Notification sent!")
return {'statusCode': 200, 'body': json.dumps(f"{issue_count} old issues checked.")}
except Exception as e:
print(f"Error: {e}")
return {'statusCode': 500, 'body': json.dumps('Error checking issues')}

이 람다 함수도 DynamoDB를 스캔할 수 있어야 하기에 권한을 설정해야 합니다. 람다 메인 페이지에서 Configuration -> Permission에서 role name을 클릭합니다.

arc.png

이전에 했던 것처럼 Add permissions -> Create inline policy를 클릭합니다.

arc.png

똑같이 JSON으로 변경 후 json을 입력합니다.

arc.png

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Statement1",
"Effect": "Allow",
"Action": ["dynamodb:Scan"],
"Resource": "*"
},
{
"Sid": "Statement2",
"Effect": "Allow",
"Action": ["sns:Publish"],
"Resource": "*"
}
]
}

이후 동일하게 next 버튼을 누르고, 이름을 설정하면 됩니다.

arc.png

Eventbridge 생성

다음으로 EventBridge로 갑니다. EventBridge Schedule을 선택하고 Create 합니다.

arc.png

다음과 같이 설정합니다. pattern은 Reccuring schedule로 설정하고 Schedule type은 Rate-based schedule로, Rate expression은 5분으로 설정합니다. 5분마다 scheduler가 람다 함수를 트리거하는 설정입니다.

arc.png

arc.png

람다 함수를 target으로 설정하고 CheckOldIssues 함수를 선택합니다.

arc.png

arc.png

EventBridge에 람다를 invoke 할 수 있는 권한을 부여할 필요 없이, target을 Lambda function으로 설정하면 자동으로 Lambda를 invoke 할 수 있는 권한이 생성됩니다. Optional 부분은 다 기본 값으로 놔두시고 Create 하시면 됩니다.

arc.png arc.png

다시 DynamoDB의 Explore items에 들어가 아까 만든 테이블을 클릭해서 현재 opend 상태인 이슈를 확인합니다. 이슈가 몇 개 담겨있는지는 만든 사람에 따라 다릅니다.

arc.png

문자도 잘 오는 것을 확인할 수 있습니다.

arc.png