Welcome to Day 13 of 100 Days of DevOps, Let’s continue this journey.
The simple goal is: save cost
Problem : Shutdown all EC2 versions in AWS Dev account at 6pm and open it again the next day at 9am (Monday to Friday). Actually this request still has a few of you.
Solution : You can use the Lambda function in combination with the CloudWatch Events to do this.
One of the big challenges in doing this is for developers who need to work late and he wants to run his instance past 6pm and have urgent patches working on weekends? A common solution I offer is to specify manual lists in Python Code (Lamda function).
Step 1 : We create the IAM Role so that Lambda can interact with the CloudWatch Event
Go to IAM Console https://console.aws.amazon.com/iam/home?region=us-west-2#/home -> Roles -> Create role
Next, select Create policy, IAM Policy will look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | { “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”: “*” } ] } |
Step 2 : Create a Lambda function
- Go to Lambda https://us-west-2.console.aws.amazon.com/lambda/home?region=us-west-2#/home
- Then choose Create Function
- Select Author from scratch
- Name: Give your Lambda function any name
- Runtime: Select Python2.7 as runtime
- Role: Choose the role we create in first step
- Click on Create function
In the next scenario we will create a function to stop / start instance
Stop instance code:
1 2 3 4 5 6 7 8 | import boto3 region = 'XX-XXXXX-X' instances = ['X-XXXXXXXX'] def lambda_handler(event, context): ec2 = boto3.client('ec2', region_name=region) ec2.stop_instances(InstanceIds=instances) print 'stopped your instances: ' + str(instances) |
Note:
- Change the Value of region
- In the instance field specify instance id
Start instance code:
1 2 3 4 5 6 7 8 | import boto3 region = 'XX-XXXXX-X' instances = ['X-XXXXXXXX'] def lambda_handler(event, context): ec2 = boto3.client('ec2', region_name=region) ec2.start_instances(InstanceIds=instances) print 'started your instances: ' + str(instances) |
Step 3 : Create CloudWatch event to activate this Lambda function
- Open the Amazon CloudWatch console.
- Choose Events, and then choose Create rule.
- Choose Schedule under Event Source.
The same goes for the Start instance
Note: here you adjust the crontab structure as you like (default according to UTC TimeZone)
Lambda function -> Monitoring -> View logs in CloudWatch
When the instance is stopped it is similar.
the start is the same.
So you have saved a lot of costs for your company already, then proposed that Tet bonus money for me =))
Good luck .
Reference: https://techzones.me/devops/stop-start-ec2-instance-on-schedule-basis-to-save-cost/