[JAVA] Serverless Framework template to schedule start / stop EC2 on Lambda
This is the 16th day article of AWS Lambda Advent Calendar 2017.
Introduction
- Nowadays with containers, I haven't touched Lambda or Serverless Framework for a long time, but since the requirement to start EC2 at 8 o'clock and stop at 20:30 has emerged, I made it with sls quickly.
- The source is available on Github.
- The content is extremely simple, so I think it can be achieved in haste.
Setting up the environment
- Please refer to Previous article.
https://qiita.com/ukitiyan/items/945d84282726d3fe2c2f
Deploy with Serverless Framework
Get source
- Get the source from the following Github.
$ git clone https://github.com/ukitiyan/operation-ec2-instance.git
Import to STS (Eclipse)
- Start STS and select the "operation-ec2-instance" folder you got from Github earlier in Project Explorer-> Right Click-> Maven-> Existing Maven Projects.
Modify serverless.yml + Build
- Modify the settings around L37 in serverless.yml as appropriate.
- rate: AWS Lambda --Schoned Event Cron Format
and described in ʻUTC`
- instanceId: Describe the instanceId of the target instance
- Schedule can be increased vertically, so it can support multiple instances. (Based on that, instanceId is not specified in the environment variable)
serverless.yml
- schedule:
rate: cron(30 11 * * ? *)
input:
goal: stop
instanceId: i-XXXXXXXXXXXXXXXXX
- schedule:
rate: cron(0 23 * * ? *)
input:
goal: start
instanceId: i-XXXXXXXXXXXXXXXXX
- Right-click on the project-> Run As-> Maven Install to build.
- Operation-ec2-instance.1.0.0.jar will be created under target.
Deploy
- As in the example, the following command is one shot.
$ cd operation-ec2-instance
$ serverless deploy -v
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
・
・
Serverless: Stack update finished...
Service Information
service: operation-ec2-instance
stage: prod
region: ap-northeast-1
api keys:
None
endpoints:
None
functions:
aws-java-maven-prod-hello: arn:XXXXXXXX
- Do
test
from the console with the following Json, or wait until the set time is reached and make sure there is no problem.
{
"goal": "stop",
"instanceId": "i-XXXXXXXXXXXXXXXXX"
}
Summary
- Well, it's a defeat. I was able to realize haste.
- It's really nice for the app shop to complete with STS.