Automate EC2 Instance Start/Stop Using AWS Lambda.

AWS is one of the most purpler cloud service providers and most of the companies, individuals are using features are used in here. If user wants to start/stop EC2 instances after the R&D is done, why do we pay more for some 3rd party applications. Now you can use AWS Lambda instead of other 3rd party applications.

aws-lambda

AWS Lambda is free for up to some level as follows. And instance start/stop can be integrated with a Lambda function in order to accomplish the task. A lambda function is where we list the task that we want to execute during lambda function runs.


Free Tier
1M REQUESTS
per month
400,000 GB-SECONDS
of compute time per month.

The Lambda free tier does not automatically expire at the end of your 12 month AWS Free Tier term, but is available to both existing and new AWS customers indefinitely.


Let’s start to create lambda function and integrate with EC2 instance administration. Please follow the given steps, if you see anything to be added or changed, please be patient to comment.

  1. Log in to the AWS console and open AWS Lambda. Then you’ll be able to see the Lambda’s homepage, and then click on create a new function.
    lambda-create-function
  2. As you can see on the create page, click on from scratch, enter a name and select Python 2.7 as Runtime. Then select “create a custom role”. When you select a custom role, you will be directed to a new page for creating the custom rule.
    lambda-fill-description
  3. Add role name and the custom policy in the Json edit part of the page. Copy and paste the Json code in the json edit area.
     {
     "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": "*"
     }
     ]
    }

    lambda-add-rule

  4. Go back to the lambda function “create page” and select “Choose an existing Rule” and select the appropriate role name, then click create function.
  5. Once you have created the function, you’ll be able to see the congratulations message on the function dashboard.
    lambda-function
  6. Now it’s time to embed the Python script for auto start & stop. Copy and paste the code given below and change the instance IDs in the script.
    import boto3
    # Specify the region where your insatnces are running. For example 'us-east-1'
    region = 'us-east-1'
    # Specify the insatnce IDs that you want to start at specific time. For example, ['xxxxxxx1', 'xxxxxxxx2']
    instances = ['xxxxxxxxxxxxxxxxxx']
    def lambda_handler(event, context):
     ec2 = boto3.client('ec2', region_name=region)
     ec2.start_instances(InstanceIds=instances)
     print 'started your instances: ' + str(instances)

    Change the following values in the scripts in as per your EC2 dashboard.
    region = ‘us-east-1’
    instances = [‘xxxxxxxxxxxxxxxxxx’]

    Additional Note: If you wish to use this script for stop instance, you can use the following line to, with new Lambda function.
    ec2.start_instances(InstanceIds=instances) => ec2.stop_instances(InstanceIds=instances)

  7. After the python script is done, save the file.
  8. Now, we can define the time to start instance using AWS Cloudwatch. Open the cloudwatch and go to the events page and click “create rule”.In this case we are going to define the instance start time with a cron job.
    First check scheduler and then check cron expression. In this case, I created a cron expression : 8 3 * * ? *
    lambda-cloudwatch-create role
  9. After that, we need to select the appropriate Lambda function to bind with our timings. Select the appropriate lambda function and click on configure details.
    lambda-function-select
  10. Enter a proper name for the rule and save.
    lambda-cloudwatch-rule-details

Now, you all done, for testing those lambda functions, you can set near time to start and stop and monitor ec2 instance.

Please comment if you would face any issues. 🙂

Thank You everyone.

Leave a comment