First, we have to create I am role that role has permission to start and stop ec2 instance.
Second, we have to create lambda functions.
Third, we have to create CloudWatch event for cron jobs.
Now create two lambda functions, one for start and second for stop to ec2 instance.
How to create lambda functions?
First click on create function
Now define the name of function, runtime(language), select an existing role which we had created and click on create function.
Now, define the lamda_function_code:-
region = ‘ap-south-1’
instances = [‘instance’]
ec2 = boto3.client(‘ec2’, region_name=region)
def lambda_handler(event, context):
print(‘started your instances: ‘ + str(instances))
After this click on deploy and give the name to the event, and test the event.
Now we are going to define the cron job, first go to CloudWatch and select rule under the event section. Select schedule section and then cron section:-
Now click on add targets and select lambda function in drop down section, define the details like which lambda function you want to trigger.