Function stop instance

Create a Lambda Function that executes Stop instances

  1. Go to AWS Management Console
  • Find Lambda
  • Select Lambda

Create Lambda Function for Stop instance

  1. In the AWS Lambda interface
  • Select Function
  • Select Create function

Create Lambda Function for Stop instance

  1. In the Create function interface
  • Select Author from scratch
  • Function name, enter dc-common-lambda-auto-stop
  • Runtime, select Python 3.8
  • Select x86_64

Create Lambda Function for Stop instance

  1. Continue in Create function interface
  • Select Change default execution role
  • Select Use an existing role
  • Select dc-common-lambda-role
  • Select Create function

Create Lambda Function for Stop instance

  1. After creating the function successfully
  • Select Configuration
  • Select Environment variables
  • Select Edit

Create Lambda Function for Stop instance

  1. In the Edit environment variables interface
  • Select Add environment variable

Create Lambda Function for Stop instance

  1. In the Edit environment variables interface
  • Key, enter environment_auto
  • Value, enter true

Create Lambda Function for Stop instance

  1. After creating the environment
  • We choose Code

Create Lambda Function for Stop instance

  1. In the Code source interface
  • Import source code: You need to change webhook_url to receive notifications to Slack.
import boto3
import os
import json
import urllib3

ec2_resource = boto3.resource('ec2')
http = urllib3.PoolManager()
webhook_url = "https://hooks.slack.com/services/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"

def lambda_handler(event, context):
    environment_auto= os.environ.get('environment_auto')
    if not environment_auto:
        print('Target is empty')
    else:
        instances = ec2_resource.instances.filter(
            Filters=[{'Name': 'tag:environment_auto', 'Values': [environment_auto]}]
        )     
        if not list(instances):
            response = {
                "statusCode":500,
                "body": "Target Instance is None"
            }
        else:
            action_stop = instances.stop()
            sent_slack(action_stop)
            response = {
                "statusCode":200,
                "body": "EC2 Stopping"
            }
        return response


def sent_slack(action_stop):
    list_instance_id = []
    if (len(action_stop)>0) and ("StoppingInstances" in action_stop[0]) and (len(action_stop[0]["StoppingInstances"])>0):
        for i in action_stop[0]["StoppingInstances"] :
            list_instance_id.append(i["InstanceId"])
            msg = "Stopping Instances ID:\n %s" %(list_instance_id)
            data = {"text":msg}
            r = http.request("POST",
                webhook_url,
                body = json.dumps(data),
                headers = {"Content-Type":"application/json"})
    else:
        print ('Not found Instances Stop')

Create Lambda Function for Stop instance

  1. Then save and select Deploy

Create Lambda Function for Stop instance

  1. Go to AWS Management Console
  • Find CloudWatch
  • Select CloudWatch

Create Lambda Function for Stop instance

  1. In the CloudWatch interface
  • Select Events
  • Select Rules
  • Select Go to Amazon EvenBridge

Create Lambda Function for Stop instance

  1. In the Rules interface
  • Select Create rule

Create Lambda Function for Stop instance

  1. In the create rule interface
  • Name, enter dc-common-lambda-auto-stop
  • Description, enter dc-common-lambda-auto-stop
  • Select Schedule
  • Select Next

Create Lambda Function for Stop instance

  1. In Schedule pattern
  • There are 2 Schedule patterns to choose from:
  • A detailed schedule that runs at a specific time, such as 8am PST on the first Monday of each month.
  • Schedule runs at a regular pace, such as every 10 minutes
  • Select A schedule that runs at a regular rate, such as every 10 minutes.
  • Set rate, value is 9 hours
  • Select Next

Create Lambda Function for Stop instance

  1. In the Target interface
  • Select AWS service
  • Select Lambda function
  • Function, select dc-common-lamda-auto-stop
  • Select Next

Create Lambda Function for Stop instance

  1. Select Next

Create Lambda Function for Stop instance

  1. Check again and select Create rule

Create Lambda Function for Stop instance

  1. Complete rule creation for stop instance

Create Lambda Function for Stop instance