Read trending IT updates for cloud businesses, managed service providers, IT pros & what innovation digital transformation is driving in tech industry.

Begin EC2 situations everytime you want, by way of AWS CloudFormation!

0 54

On this article, I’ve articulated how we will START the stopped EC2 situations as and after we want. Automating the beginning of EC2 situations every day at particular time intervals like begin of the day (when stopped earlier evening) can be an actual value optimizing step.


Earlier than we glance into the cloudformation script instantly, please just be sure you have atleast one EC2 occasion in STOPPED state. Additionally, Please learn my earlier article on stopping the situations by way of CFN as one might require the script for that as properly.

What the script does?

Beginning EC2 situations utilizing cloudformation includes the next steps. The cloudformation script would do all of the beneath talked about steps.

  1. Creating a job for lambda and fasten a coverage with permission to Begin the EC2 situations.

  2. Making a lambda occasion handler to execute a script (Python script in our instance) for beginning EC2 situations.

  3. Create a script to start out EC2 situations by working the lambda occasion handler on the particular time and particular days.

Right here, the particular time and days are offered within the type of a CRON expression. So one want to obviously perceive the CRON expression earlier than working the CFN script.

This script has been taken from AWS documentation however I’ve modified and separated the scripts for STOP and START actions.

Understanding CRON Expression

For extra info on CRON expression, please comply with the amazon documentation hyperlink.

Cloud formation script to START (or schedule to start out) situations at any time when we want.

AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda operate with cfn-response.
 Default: i-0506f7d826a359c4f
 Description: Occasion ID's seperated by commers 
 Sort: String
 Default: ap-southeast-1
 Description: area just one area supported 
 Sort: String
 Default: cron(0 7 ? * MON-SUN *)
 Description: enter an Schedule expression instance cron(0 7 ? * MON-FRI * ) see https://docs.aws.amazon.com/AmazonCloudWatch/newest/occasions/ScheduledEvents.html
 Sort: String
 Sort: AWS::Lambda::Operate
 Runtime: python3.8
 Position: !GetAtt Position.Arn
 Handler: index.lambda_handler
 Timeout: 60
 situations: !Ref situations
 Area: !Ref Area
 ZipFile: |
          import json
          import re
          import os
          import boto3
          def lambda_handler(occasion, context):
            # TODO implement
            instances_str = os.environ['instances']
            area = os.environ['Region']
            ec2 = boto3.consumer('ec2', region_name=area)
            situations= re.findall(r"i-[0-9a-z]{17}|i-[0-9a-z]{8}", instances_str)
            print('began your situations: ' + str(situations)+ "in Area "+ area)
            return {
              'statusCode': 200,
              'physique': json.dumps('began your situations: ' + str(situations))
 Description: Operate that began situations
 Sort: AWS::Lambda::Permission
 FunctionName: !GetAtt StartEC2Instances.Arn
 Motion: lambda:InvokeFunction
 Principal: occasions.amazonaws.com
 "SourceArn" : !GetAtt StartScheduledRule.Arn

 Sort: 'AWS::IAM::Position'
 Model: 2012-10-17
          - Impact: Permit
              - lambda.amazonaws.com
              - 'sts:AssumeRole'
 Path: /
        - "arn:aws:iam::aws:coverage/service-role/AWSLambdaBasicExecutionRole"
 Insurance policies:
        - PolicyName: Ec2permissions
 Model: 2012-10-17
              - Impact: Permit
                - "ec2:StartInstances"
 Useful resource: '*'
 Sort: AWS::Occasions::Rule
 Description: "ScheduledRule"
 ScheduleExpression: !Ref StartScheduled
 State: "ENABLED"
 Arn: !GetAtt StartEC2Instances.Arn
 Id: "TargetFunctionV1"

Formatted Script

The right way to execute the script?

As talked about within the pre-cursor part, to execute the START script, you have to guarantee that you’ve got a number of EC2 situations in STOPPED state.

  1. Enter the stopped occasion(s) Id within the cloud formation within the situations discipline below parameters part.

  2. Enter the suitable area of your EC2 occasion(s)

  3. Enter the hours, minutes and the times within the CRON expression both within the script or within the CRON discipline whereas importing

  4. Add the script in CloudFormation on clicking Create Stack

5. click on on Subsequent, present a reputation to the stack and enter the time to cease the EC2 occasion within the StartScheduled discipline.

6. Click on on the acknowledgement for creating a job and create the stack. The stack runs efficiently.

7. As soon as the script has been efficiently run, verify the standing of the occasion below EC2

8. Additionally, verify for the lambda operate being created within the Lambda part.


If you don’t want to Begin or schedule that begin time on a regular basis and wish to begin situations at an adhoc foundation, you would simply go forward run the stack by offering the hours and minutes on the CRON expression after which delete the stack when occasion is began.

I hope the above article shall be helpful for a lot of AWS customers who wish to begin the stopped EC2 situations mechanically on want foundation.

In case you discover this text useful, kindly share this along with your identified teams and likewise present your useful feedback right here. Thanks.

You might also like