【AWS】Lmabdaでinstance(running)を監視してslackに通知する


起動しているインスタンスをチェックして通知します。

クーロンで回す想定で書いてます。お遊び

外部モジュールのslackwebを使っているのでローカルでzip化してアップロードします。
その辺は過去の記事に書いているので参考にしてみてください。
slack周りの設定はここに詳しく書いてます。

lambda_function.py
from __future__ import print_function
import json
import slackweb
import boto3



ec2 = boto3.client('ec2')
SLACK_POST_URL = "https://hooks.slack.com/*****"




def lambda_handler(event, context):
    print('Loading function')
    result = chk_running_instances()
    if result == []:
        slack_post("[INFO] 0 running-instance ")
    else:
        i = len(result)
        for a in range(0, i):
            instance_id = result[a].keys()
            instance_type = result[a].values()
            post_message = "[INFO] Running instance is... instance_id: %s, instance_type: %s"%(instance_id, instance_type)
            slack_post(post_message)




def chk_running_instances():
    response = ec2.describe_instances(
        Filters=[
            {
                'Name': 'instance-state-name',
                'Values': [
                    'running',
                ],
            },
        ],
    )

    instance_ids = []
    instance_type = []
    info = []
    i = len(response['Reservations'])

    for a in range(0, i):
        instance_ids.insert(a, response['Reservations'][a]['Instances'][0]['InstanceId'])
        instance_type.insert(a, response['Reservations'][a]['Instances'][0]['InstanceType'])
        info.insert(a, {instance_ids[a]:instance_type[a]})
    return info




def slack_post(post_massage):
    slack = slackweb.Slack(url=SLACK_POST_URL)
    slack.notify(text=post_massage, username="coffee-bot", icon_emoji=":coffee:")

昔書いた書きかけの記事が出てきたので公開。
余力があったら最近書いたやつをそのうち上げる・・・