Back-end
AWS 사용요금 문자로 받기
hjr067
2024. 8. 29. 12:36

Service 아키텍처
1. MonthlyUsageSNS Lambda Function
import json
import boto3
from datetime import datetime
from dateutil.relativedelta import *
def lambda_handler(event, context):
client = boto3.client('ce')
today = datetime.today()
this_month_first_day = datetime(today.year, today.month, 1)
str_today = str(today.strftime('%Y-%m-%d'))
str_first_day = this_month_first_day.strftime('%Y-%m-%d')
#Cost Expolorer
result = client.get_cost_and_usage(
Granularity= 'MONTHLY',
TimePeriod={
'Start': str_first_day,
'End': str_today
},
Metrics=[ 'UnblendedCost',]
)
#Send Message with Amazon SNS
sns = boto3.client('sns', region_name='ap-northeast-1')
cost = float(result['ResultsByTime'][0]['Total']['UnblendedCost']['Amount'])
cost_round = round(cost, 2)
str_cost = str(cost_round)
message_content = "금일 %s 일 기준 이번 달 사용 금액은 %s 달러입니다."%(str_today, str_cost)
#Change phone number
sns.publish(PhoneNumber="+821012345678", Message=message_content )
return {
'statusCode': 200,
'body': json.dumps('Message was sent successfully!')
}
- boto3를 사용하여 AWS 서비스에 접근 !
- boto3는 python용 AWS SDK
- boto를 통해 cost explorer에 접근해 budget 정보를 긁어오고, sns로 문자 발송을 명령한다.
- 결과적으로 message_content = "금일 %s 일 기준 이번 달 사용 금액은 %s 달러입니다."%(str_today, str_cost) 라는 메세지를 보내고,
- sns.publish()를 통해 문자를 보낸다.
- ** 번호는 본인 번호로 설정하기 !!
추가적인 설정도 물론 필요하다.
1) Lambda 함수의 IAM 역할에서 두가지 권한을 부여:
- "sns:Publish" : sns publish 기능에 대한 권한
- "ce:GetCostAndUsage" : cost explorer에서 cost and usage를 get 하는 권한
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"sns:Publish",
"ce:GetCostAndUsage"
],
"Resource": "*"
}
]
}
2) SNS 도쿄 리전에서 문자메세지 샌드박스 대상 전화번호에 내 번호 등록
왜 도쿄 리전인가?
서울에선 아직 해당 기능을 지원하지 X
전화번호 추가 시 주의사항이 있다.
010-0000-0000 의 번호를 등록하는 경우, +8210100000000으로 등록해야 한다.
+82 010 0000 0000 으로 입력하지 말기 !!!
설정을 마치고 람다함수 Test 실행하기.
형식 상관 없이 아무거나 보내서 trigger 시키면 된다.
근데 ...
내가 직접 함수 호출시켜서 확인할거면 이걸 쓸 이유가 없으니,
스케줄러를 넣어서 주기적으로 실행될 수 있게 해본다면?
EventBridge의 Scheduler 사용 가능

1. 이런식으로 크론을 설정하고,
2. 호출하는 부분을 내가 만든 람다함수로 등록해주면 끝
3. Next 10 trigger dates 를 확인하면 내가 잘 설정했는지 확인할 수 있다.
** UTC 시간으로 나오니까 설정 잘 하기 ~
돈 나오기 전에 문제 해결하기에 좋을 듯 하다 >_0 !!