AWS Lambda to stop ec2 instance with cron

  • Create aws lambda function
  • Attach IAM role as required
import boto3
region = 'ap-south-1'
instances = ['i-0e4e6863cd3da57b5']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))
  • Create Cloudwatch event bus rule and attach it to lambda function