This repository contains Go code and scripts to start and stop instances. The purpose is to schedule the start and stop of EC2 instances to reduce the cost of usage. To start and stop instances, there are so many options, such as aws-cli and lambda functions.
Install AWS CLI AWS Command Line Interface
Config AWS credention
aws configure
Start instance
INSTANCE_ID=<instance_id>
aws ec2 start-instances \
--instance-ids $INSTANCE_ID
Stop instance
INSTANCE_ID=<instance_id>
aws ec2 start-instances \
--instance-ids $INSTANCE_ID
can put flag --dry-run
to check permission without making a request. ec2 cli options.
You can use the lambda function with the EventBridge to schedule the control of the EC2 instances.
-
Create an IAM policy and IAM role for your Lambda function.
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": ["ec2:Start*", "ec2:Stop*"], "Resource": "*" } ] }
-
Build a binary file by following the instructions of aws-lambda-go.
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main *.go zip main.zip main
-
Create an AWS lambda function with the granted role.
-
Upload a binary zip file.
-
Runtime settings: set handler file name to build file example
main
. -
Run test start and stop instances. example payload
{ "state": "start", "instanceIds": [ "i-0XXXXX" ] }
-
Add EventBridge as a function trigger or create the EventBridge schedule from the EventBridge console.
-
Set cron-based schedules; from my example, I will set up two schedules, one for the start instance at 8:00 a.m. and the other for the stop instance at 8:00 p.m. every day.
-
Select target as the AWS Lambda.
-
Select the function to control instances and put a payload for start or stop instances, like when you test the functions.
-
Finish!