In many use cases, you dont need to run EC2 whole day, it will be optimum to stop the ec2 when not in use. This will not just save money for you, it will save energy used to run idle server.
Following steps are required to start and stop ec2 automatically. Here we will start and stop ec2 based on cron schedule.
import boto3
region = 'ap-south-1'
instances = ['i-111111a22a399999']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
import boto3
region = 'ap-south-1'
instances = ['i-111111a22a399999']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
{ "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": "*"
}
]
}
Note: please add this policy to lambda roles from IAM, otherwise, you will get below error
[ERROR] ClientError: An error occurred (UnauthorizedOperation) when calling the StopInstances operation: You are not authorized to perform this operation. User: arn:aws:sts::012444455555:assumed-role/ec2_start-role-c0asas4ik/ec2_start is not authorized to perform: ec2:StopInstances on resource: arn:aws:ec2:ap-south-1:012444455555:instance/i-i-111111a22a399999 because no identity-based policy allows the ec2:StopInstances action.
Sample expression to run job at 9 AM in morning for all weekdays is as below
0 9 ? * MON-FRI *
post by Pravin