Skip to content

3. EC2 START STOP CRONJOB

bhupender rawat edited this page Jan 7, 2022 · 4 revisions

Managing Servers with Lambda

eventbridge aero lambda EC2 aero

So, Today we will be covering an interesting topic here i.e. how we can integrate Cloudwatch EventBridge with Lambda. As we all know that AWS Lambda is serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers.

But we also know that Lambda does not allow to use of cron, so here we will be using Scheduled Events from EventBridge to START EC2 instances from a matching tag.

Let's get down to the practical scenario, we will break it down into a few simpler steps.



Prerequisites:

  • Must have an AWS account with Administrator level permission.
  • Two EC2 Instances in the stopped state with the below tag,
    • Tags
      • env: dev

Topics:

  • Lambda Function
  • IAM Role for permission
  • Cloudwatch | EventBridge | Scheduled Event
  • Two EC2 instances are already there with the below details,
    • State: stopped
    • Tags
      • env: dev


IAM Role for Lambda


STEP 1: Search the IAM service on the search bar.



STEP 2: In the IAM Service, choose Role & click on "Create Role"




STEP 3 : Configure,

  • Select type of trusted entity : AWS Service
  • Choose a use case : Lambda



STEP 4: Attaching permission to your role.

  • Permission : AmazonEC2FullAccess


NOTE: For now we are providing full EC2 permission which is not idle. So you can modify the permissions according to the specific requirement.



STEP 5 : Provide the Role Name,

  • Name : EC2-start


Finally, Click on "create role"



Lambda Function


STEP 1: Search the Lambda service on the search bar.




STEP 2 : Click on create function.




STEP 3: In "Create function", choose "Author from scratch" as we will be deploying our own code.




STEP 4: Provide the following information,

  • Function Name : ec2-start
  • Runtime: Python 3.8 [ Multiple languages will be provided here, we are choosing Python 3.8 as our code is written on Python ]
  • Architecture : x86_64



STEP 5: In the Permission section,

  • Execution Role > Choose "Use as existing role"
  • From the drop-down menu, choose the role which you have created earlier,
    • EC2-start



STEP 6: We will use the default "Advanced settings"




STEP 7: Function "EC2-start" dashboard will look something like this, by default it provides lambda_function.py file.




STEP 8 : Here, lambda function provides handler, which is

  • lambda_function.lambda_handler
    • lambda_function : python file name
    • lambda_handler : function name inside the python file.



STEP 9: Creating python code, which will only start those instances which has tag "env : dev"


import boto3

client = boto3.client('ec2')

startresponse = client.describe_instances(
        Filters= [{"Name" :"tag:env", "Values":["dev"] }]
)


## Getting instance id - START ### 
def lambda_function(event, context):
    i = 0
    while True:
        try:
            instanceid = startresponse['Reservations'][i]['Instances'][0]['InstanceId']
            ## Starting Instances ###
            ec2 = client.start_instances(
                InstanceIds=[
                    instanceid,
                ],
            )
            i+=1
        except IndexError:
            break


STEP 10: Here, we are installing boto3 libraries into the working directory.




STEP 11: Creating a zip file named "python.zip"




STEP 12: Upload your zip file into Lambda Function.




STEP 13: Choose the zip file from your PC & hit the "save"



STEP 14: Edit the default run time settings, as we have seen on STEP 8. Changing it to,

  • python.lambda_function

NOTE - By default lambda provides the handler as "lambda_function.lambda_handler". Here,

- lambda_function = your python file name.
- lambda_handler = your function name inside the python file.

These two things are mandatory, if provided incorrectly then your function will fail.



Cloudwatch | EventBridge | Scheduled Event

STEP 1 : Search the service "Cloudwatch".



STEP 2 : Choose,

  • Events
    • Rules


STEP 3: Choose "Go to Amazon EventBridge"



STEP 4: Will be choose the default event bus here & then click on "Create Rule".



STEP 5: Provide the details,

  • Name : EC2-start
  • Description: Starting the EC2 instances


STEP 6 : In the pattern section,

  • Choose "Schedule event"
  • Choose "Cron Expression" & set it for 8am
    • 30 2 * * ? *



STEP 7 : will go with default settings,




STEP 8 : In the Target section,

  • Choose "Lambda Function"
  • Function : EC2-start



STEP 9: provide the tags accordingly.




STEP 10: Your dashboard will look like,




Finally, when the cronjob triggers your Lambda function at 08:00 am IST which we have defined earlier then your EC2 instances will automatically get into a running state.



Similarly, you can create a new lambda function to STOP the EC2 instances at a specific time.

Clone this wiki locally