Python Scripts : Start/Stop AWS EC2

Akhil C K
1 min readMay 11, 2021

Services → Lambda → Functions → Create function

Choose create custom rule → Give role name → Edit Policy document as below

{
"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": "*"
}
]
}

Click Allow → Give lambda function name ‘ec2start’ → Next

Put below code to the body of lambda function

import boto3
region = '' ## region, eg: us-east-1
instances = [''] ##instance ids
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.start_instances(InstanceIds=instances)
print 'started your instances: ' + str(instances)

You can add triggers for this lambda function. It is available under

Designer → CloudWatch events → Create new rule

We can provide schedule expression here.

To Stop the instance we can create another lambda function. Please use following code.

import boto3
region = '' ## region, eg: us-east-1
instances = [''] ##instance ids
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + str(instances)

Thats it, Enjoy!

--

--