Stop EC2 for specified time + start with Lambda (python)

Lambda setting for stop

Select Lambda

Select blank function in blueprint selection

Lambda1.png

Next without setting the trigger

Lambda2.png

Set the function

Lambda3.png

Name:StopEC2 Description:stop EC2 Runtime: Python2.7

In the code of the Lambda function Described the code for stopping the instance.

python


import boto3

region = 'ap-northeast-1'
instances = ['X-XXXXXXXX']
def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)
    print 'stopped instances: ' + str(instances)

Set region and instances. The above specifies the Tokyo region (ap-northeast-1).

The explanation of Boto3 is as follows AWS SDK For Python (Boto3) https://aws.amazon.com/jp/sdk-for-python/

Set Lambda function handlers and roles

Choose to create a new role, Set the role name and policy.

Lambda4.png

IAM_Management1.png

The role name is lambda_start_stop_ec2. The policy allows you to start and stop EC2.

Policy document


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
        "Effect": "Allow",
        "Action": [
            "ec2:StartInstances",
            "ec2:StopInstances"
        ],
        "Resource": "*"
    }
  ]
}

Press Next.

After confirmation, press Create Function.

Lambda5.png

This completes the stop.

Lambda settings for startup

It is for starting, but basically the same as for stopping, Just change "ec2.stop_instances" in the function to "ec2.start_instances" and the rest is the same. Select the role you created earlier.

Lambda6.png

CloudWatch Events settings for stopping

Select CloudWatch

Select Event → Create Rule.

CloudWatch1.png

Creating rules

Select the schedule and cron expression to set the execution time. The time zone is UTC and cron is described below. https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html

For the target, select StopEC2 of the Lambda function created earlier and perform "setting details".

CloudWatch2.png

Enter your name and description and you're done.

CloudWatch3.png

CloudWatch Events settings for startup

You can use the same description as stop except for the set time and changing the Lambda function to StartEC2.

CloudWatch Events Log

You can check it in the log of the CloudWatch menu below.

CloudWatch4.png

that's all.

Recommended Posts

Stop EC2 for specified time + start with Lambda (python)
Try automating Start / Stop for EC2 instances with AWS Lambda
Play with Lambda layer (python) for about 5 minutes
Use logger with Python for the time being
Run with CentOS7 + Apache2.4 + Python3.6 for the time being
Create a Layer for AWS Lambda Python with Docker
Operate TwitterBot with Lambda, Python
Start / stop GCE from python
Execution time measurement with Python With
Time synchronization (Windows) with Python
[Python] Create a date and time list for a specified period
Face detection with Lambda (Python) + Rekognition
Exclude specified cases with Python unittest
Getting Started with Python for PHPer-Classes
Periodically start / stop Sakura's cloud server with AWS Lambda + CloudWatch Events
See python for the first time
Notify HipChat with AWS Lambda (Python)
Start Django for the first time
Use PostgreSQL with Lambda (Python + psycopg2)
Getting Started with Python for PHPer-Functions
I want to do it with Python lambda Django, but I will stop
Try to make foldl and foldr with Python: lambda. Also time measurement
[AWS] Using ini files with Lambda [Python]
Easy keyword extraction with TermExtract for Python
INSERT into MySQL with Python [For beginners]
WEB scraping with Python (for personal notes)
Manually ssh registration for coreserver with python
Use DeepL with python (for dissertation translation)
Memo to ask for KPI with python
Amplify images for machine learning with python
Search for files with the specified extension
Tips for dealing with binaries in Python
Python Master RTA for the time being
Searching for properties to start with TensorFlow-Part 1
Manipulate DynamoDB data with Lambda (Node & Python)
Tips for using python + caffe with TSUBAME
[Shakyo] Encounter with Python for machine learning
Process multiple lists with for in Python
MongoDB for the first time in Python
Getting Started with Python for PHPer-Super Basics
Debug for mysql connection with python mysql.connector
[Python] Read images with OpenCV (for beginners)
Connect to s3 with AWS Lambda Python
WebApi creation with Python (CRUD creation) For beginners
Preparation for scraping with python [Chocolate flavor]
Try assigning or switching with Python: lambda
[For beginners] Try web scraping with Python
Python + Selenium + Headless Chromium with aws lambda
Start python
What I did when I got stuck in the time limit with lambda python
Turn multiple lists with a for statement at the same time in Python
How to start Python (Flask) when EC2 starts
AWS-Perform web scraping regularly with Lambda + Python + Cron
Causal reasoning and causal search with Python (for beginners)
Build python environment with pyenv on EC2 (ubuntu)
Get a ticket for a theme park with python
[Python3] A story stuck with time zone conversion
[Translation] Getting Started with Rust for Python Programmers
Create a LINE BOT with Minette for Python
It's time to stop generating SMILES with RDKit
Building an Anaconda environment for Python with pyenv