100 Days of AWS — Day 16- Stop/Start EC2 instance on a scheduled basis to save cost

Go to IAM Console https://console.aws.amazon.com/iam --> Roles --> Create role
{"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": "*"}]}
Go to IAM Console https://console.aws.amazon.com/iam --> Roles --> Create role
* Select Author from scratch
* Name: Give your Lambda function any name
* Runtime: Select Python3.9 as runtime
* Role: Choose the role we create in first step(ec2-stop-start-role)
* Click on Create function
import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'XX-XXXXX-X'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
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)
* Change the Value of region
* In the instance field specify instance id

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prashant Lakhera

Prashant Lakhera

4.91K Followers

AWS Community Builder, Ex-Redhat, Author, Blogger, YouTuber, RHCA, RHCDS, RHCE, Docker Certified,4XAWS, CCNA, MCP, Certified Jenkins, Terraform Certified, 1XGCP