安心・健康・痩せる方法

アンヘルシープログラマーの備忘録

How to start and stop EC2 with AWS lambda

sorry! my english slill is very low!

英語で書いた方がアクセス数稼げるんでね?って推測を基に怪しい日本語と英語で記事を書いてみようと思います。(en: i think tech blog what written by english can get more access, so I challenge to write blog in English.)

I write start/stop EC2 and set and register_instances_with_load_balancer/ deregister_instances_from_load_balancer.

EC2をlambdaで開始する方法(en:How to start EC2 with lambda?)

runtime: python3.6

import sys
import boto3
import os

client = boto3.client('ec2')
ec2 = boto3.resource('ec2')

elb_client= boto3.client('elb')

instance_id = os.environ['INSTANCEID']
elb_name = os.environ['ELBNAME']

def handler(event, context):
    # start EC2
    response = client.start_instances(InstanceIds=[instance_id,])
    instance = ec2.Instance(id=instance_id)
    instance.wait_until_running() 

    # add elb 
    response = elb_client.register_instances_with_load_balancer(
        LoadBalancerName=elb_name,
        Instances=[
            {'InstanceId': instance_id},
            ]
        )

we need set Environment variable like this

f:id:darakunomiti:20171217112716j:plain

EC2をlambdaで終了する方法(en:How to stop EC2 with lambda?)

runtime: python3.6

import sys
import boto3
import os
from time import sleep

client = boto3.client('ec2')
elb_client= boto3.client('elb')

instance_id = os.environ['INSTANCEID']
elb_name = os.environ['ELBNAME']

def handler(event, context):
  
    response = elb_client.deregister_instances_from_load_balancer(
        LoadBalancerName=elb_name,
        Instances=[
            {'InstanceId': instance_id},
            ]
        )
    sleep(10)
    
     response = client.stop_instances(InstanceIds=[instance_id4,])