Skip to content

Instantly share code, notes, and snippets.

@smd877
Created February 1, 2020 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smd877/2d02b3a8a771ded7d69a9c2b16e73bc8 to your computer and use it in GitHub Desktop.
Save smd877/2d02b3a8a771ded7d69a9c2b16e73bc8 to your computer and use it in GitHub Desktop.
AWSのコストとEC2の状況をLINEで報告するLambda
#coding: UTF-8
import os
import boto3
import json
import copy
import urllib.request, urllib.parse
from datetime import datetime, timedelta
URL = 'https://api.line.me/v2/bot/message/push'
def lambda_handler(event, context):
contents = get_contents()
title = '{}の報告'.format(datetime.now().strftime('%Y/%m/%d'))
contents['body']['contents'][0]['text'] = title
dynamics = contents['body']['contents'][1]['contents']
cost = getCurrentCost(boto3.resource('cloudwatch', region_name='us-east-1'))
dynamics.append(dynamic_element('Cost', cost))
dynamics.append({'type': 'separator'})
running_count = 0
for instance in boto3.resource('ec2').instances.all():
tags = dict([(tag['Key'], tag['Value']) for tag in instance.tags])
dynamics.append(dynamic_element(tags['Name'], instance.state['Name']))
running_count += 1 if instance.state['Name'] == 'running' else 0
contents['body']['backgroundColor'] = "#FF7F7F" if running_count > 1 else "#7FFF7F"
body = get_body(os.environ['SEND_TO'], title, contents)
post_line(os.environ['CHANNEL_TOKEN'], body)
return {
'statusCode': 200,
'body': json.dumps(body)
}
def post_line(token, body):
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
req = urllib.request.Request(URL, data=json.dumps(body).encode("utf-8"),headers=headers,method='POST')
urllib.request.urlopen(req)
def getCurrentCost(cloudwatch):
data = cloudwatch.Metric('AWS/Billing', 'EstimatedCharges').get_statistics(
Dimensions=[{'Name': 'Currency', 'Value': 'USD'}],
StartTime=datetime.today() - timedelta(days = 1),
EndTime=datetime.today(),
Period=86400,
Statistics=['Maximum'])
try:
cost = data['Datapoints'][0]['Maximum'] if len(data['Datapoints']) > 0 else 0
return '{} dollars'.format(cost)
except:
return 'Error'
def get_contents():
return {
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "title here.",
"weight": "bold"
},
{
"type": "box",
"layout": "vertical",
"contents": []
}
],
"backgroundColor": "color here."
}
}
def dynamic_element(key, value):
return {
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "text",
"text": key
},
{
"type": "text",
"text": value
}
]
}
def get_body(to, altText, contents):
return {
'to': to,
'messages': [{
"type": "flex",
"altText": altText,
"contents": contents
}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment