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

Cease EC2 cases everytime you want, by AWS CloudFormation!

0 41

On this article, I’ve articulated how we are able to STOP EC2 cases as and after we want. There could also be instances after we truly do not want EC2 cases working however terminating them might lead to loosing the occasion utterly. So many desire to cease the cases as a substitute and automating this to schedule day by day at particular time intervals like weekends or after work hours can be an actual value optimizing step.

Pre-cursor

Earlier than we glance into the cloudformation script immediately, lets look how we will likely be stopping the cases utilizing CFN. Once we truly look into the steps concerned in stopping EC2 utilizing CFN, a few of it’s possible you’ll suppose that stopping cases manually as a substitute can be easy (like simply clicking a button). However we want somebody to all the time manually cease the cases at odd instances and right here comes the advantage of automating it.

What the script does?

Stopping EC2 cases utilizing cloudformation includes the next steps. The cloudformation script would do all of the under talked about steps.

  1. Creating a job for lambda and fix a coverage with permission to cease the EC2 cases.

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

  3. Create a script to cease EC2 cases by runing the lambda occasion handler on the particular time and particular days.

Right here, the particular time and days are supplied 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 observe the amazon documentation hyperlink.

Cloud formation script to STOP (or schedule to cease) cases every time we want.

AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda operate with cfn-response.
Parameters: 
 cases: 
 Default: i-0c33ad649583812e1
 Description: Occasion ID's separated by commas 
 Sort: String
 Area: 
 Default: ap-southeast-1
 Description: area solely 1 area supported 
 Sort: String
 StopScheduled: 
 Default: cron(0 18 ? * MON-SUN *)
 Description: enter an Schedule expression instance cron(0 18 ? * MON-FRI *) see https://docs.aws.amazon.com/AmazonCloudWatch/newest/occasions/ScheduledEvents.html
 Sort: String

Sources:
 StopEC2Instances:
 Sort: AWS::Lambda::Operate
 Properties:
 Runtime: python3.8
 Position: !GetAtt Position.Arn
 Handler: index.lambda_handler
 Timeout: 60
 Surroundings:
 Variables:
 cases: !Ref cases
 Area: !Ref Area
 Code:
 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.shopper('ec2', region_name=area)
            cases= re.findall(r"i-[0-9a-z]{17}|i-[0-9a-z]{8}", instances_str)
            print('stopped your cases: ' + str(cases) + "in Area "+ area)
            ec2.stop_instances(InstanceIds=cases)
 
            return {
              'statusCode': 200,
              'physique': json.dumps('stopped your cases: ' + str(cases))
            }
 Description: Operate that stops cases
 permissionForEventsToInvokeStopEC2Instances:
 Sort: AWS::Lambda::Permission
 Properties:
 FunctionName: !GetAtt StopEC2Instances.Arn
 Motion: lambda:InvokeFunction
 Principal: occasions.amazonaws.com
 "SourceArn" : !GetAtt StopScheduledRule.Arn

 Position:
 Sort: 'AWS::IAM::Position'
 Properties:
 AssumeRolePolicyDocument:
 Model: 2012-10-17
 Assertion:
          - Impact: Enable
 Principal:
 Service:
              - lambda.amazonaws.com
 Motion:
              - 'sts:AssumeRole'
 Path: /
 ManagedPolicyArns:
        - "arn:aws:iam::aws:coverage/service-role/AWSLambdaBasicExecutionRole"
 Insurance policies:
        - PolicyName: Ec2permissions
 PolicyDocument:
 Model: 2012-10-17
 Assertion:
              - Impact: Enable
 Motion:
                - "ec2:StopInstances"
 Useful resource: '*'
 
 StopScheduledRule: 
 Sort: AWS::Occasions::Rule
 Properties: 
 Description: "ScheduledRule"
 ScheduleExpression: !Ref StopScheduled
 State: "ENABLED"
 Targets: 
        - 
 Arn: !GetAtt StopEC2Instances.Arn
 Id: "TargetFunctionV1"

Formatted Script

Learn how to execute the script?

To execute the STOP script you need to guarantee that you’ve got a number of EC2 cases working.

  1. Enter the occasion(s) Id within the cloud formation within the cases area beneath 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 area 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 StopScheduled area.

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 beneath EC2

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

TIP:

If you don’t want to cease or schedule on a regular basis and need to cease cases at an adhoc foundation, you could possibly simply go forward run the stack by offering the hours and minutes on the CRON expression after which delete the stack when occasion is stopped.

I hope the above article will likely be helpful for a lot of AWS customers who need to cease the EC2 cases as a substitute of terminating, on want foundation. My subsequent article will likely be clearly on how you can START stopped EC2 cases with the same script.

When you discover this text useful, kindly share this together with your identified teams and in addition present your invaluable feedback right here. Thanks.

You might also like
Loading...