LoginSignup
3
1

More than 5 years have passed since last update.

SORACOM LTE-M Button+AWS LambdaでEC2インスタンスの状態を操る

Last updated at Posted at 2018-11-07

はじめに

タイトルそのままです。
SORACOM LTE-M Buttonを買ったので同一リージョン内のインスタンスの起動・停止・再起動をボタンだけでできるようにしました。

注意

Lambda関数のIAMロールを設定しましょう。
この辺りが参考になると思います

AWS Lambda上での実装(Python 3.6)

今回は1回押すと起動/2回押すと再起動/長押しで停止するようにします。

IoTEC2Button.py
from __future__ import print_function

import boto3
import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)



def lambda_handler(event, context):
    logger.info('Received event: ' + json.dumps(event))
    #今回は東京リージョン内のインスタンスを操作するのでap-northeast-1
    client = boto3.client('ec2','ap-northeast-1')
    responce = client.describe_instances()
    #全インスタンスIDを入れておく配列
    all_list = []
    for reservation in responce['Reservations']:
      for instance in reservation['Instances']:
          ##ステータスがterminatedになっているインスタンスがあるときのエラー対策
          if instance['State']['Name'] != "terminated":
              all_list.append(instance['InstanceId'])
    click_type = event['deviceEvent']['buttonClicked']['clickType']
    #操作対象のインスタンスのID(個別で操作したい場合はここに操作対象のインスタンスIDを入れる)
    ilist=list(all_list)
    #1回押した時
    if click_type == "SINGLE":
        start =  client.start_instances(InstanceIds=ilist)
        return start
    #2回押した時
    elif click_type == "DOUBLE":
        reboot =  client.reboot_instances(InstanceIds=ilist)
        return reboot
    #長押しした時
    elif click_type == "LONG":
        forcestop =  client.stop_instances(InstanceIds=ilist,Force=True)
        return forcestop
    logger.info('OK') 

おわりに

LTE-Mボタンは外出先でも使えるので使う時だけ起動/作業終わったら停止させればコストも減らせて非常に便利です。
インスタンス常時稼働させとくとコストが...ただいちいちコンソール開くのもなぁ...なんて面倒くさがりな方(主に私)にもいいかもしれません。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1