Function stop instance

Tạo Lambda Function thực hiện chức năng Stop instances

  1. Truy cập AWS Management Console
  • Tìm Lambda
  • Chọn Lambda

Create Lambda Function for Stop instance

  1. Trong giao diện AWS Lambda
  • Chọn Function
  • Chọn Create function

Create Lambda Function for Stop instance

  1. Trong giao diện Create function
  • Chọn Author from scratch
  • Function name, nhập dc-common-lambda-auto-stop
  • Runtime, chọn Python 3.8
  • Chọn x86_64

Create Lambda Function for Stop instance

  1. Tiếp tục trong giao diện Create function
  • Chọn Change default execution role
  • Chọn Use an existing role
  • Chọn dc-common-lambda-role
  • Chọn Create function

Create Lambda Function for Stop instance

  1. Sau khi tạo function thành công
  • Chọn Configuration
  • Chọn Environment variables
  • Chọn Edit

Create Lambda Function for Stop instance

  1. Trong giao diện Edit environment variables
  • Chọn Add environment variable

Create Lambda Function for Stop instance

  1. Trong giao diện Edit environment variables
  • Key, nhập environment_auto
  • Value, nhập true

Create Lambda Function for Stop instance

  1. Sau khi tạo môi trường xong
  • Chúng ta chọn Code

Create Lambda Function for Stop instance

  1. Trong giao diện Code source
  • Import source code: Bạn cần phải thay đổi webhook_url để nhận thông báo đến 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. Sau đó lưu lại và chọn Deploy

Create Lambda Function for Stop instance

  1. Truy cập AWS Management Console
  • Tìm CloudWatch
  • Chọn CloudWatch

Create Lambda Function for Stop instance

  1. Trong giao diện CloudWatch
  • Chọn Events
  • Chọn Rules
  • Chọn Go to Amazon EvenBridge

Create Lambda Function for Stop instance

  1. Trong giao diện Rules
  • Chọn Create rule

Create Lambda Function for Stop instance

  1. Trong giao diện create rule
  • Name, nhập dc-common-lambda-auto-stop
  • Description, nhập dc-common-lambda-auto-stop
  • Chọn Schedule
  • Chọn Next

Create Lambda Function for Stop instance

  1. Trong Schedule pattern
  • Có 2 Schedule pattern để lựa chọn:

    • Lịch trình chi tiết chạy vào một thời điểm cụ thể, chẳng hạn như 8 giờ sáng theo giờ PST vào Thứ Hai đầu tiên của mỗi tháng.
    • Lịch trình chạy với tốc độ đều đặn, chẳng hạn như 10 phút một lần
  • Chọn A schedule that runs at a regular rate, such as every 10 minutes.

  • Đặt rate, value là 9 hours

  • Chọn Next

Create Lambda Function for Stop instance

  1. Trong giao diện Target
  • Chọn AWS service
  • Chọn Lambda function
  • Function, chọn dc-common-lamda-auto-stop
  • Chọn Next

Create Lambda Function for Stop instance

  1. Chọn Next

Create Lambda Function for Stop instance

  1. Kiểm tra lại và chọn Create rule

Create Lambda Function for Stop instance

  1. Hoàn thành tạo rule cho stop insatance

Create Lambda Function for Stop instance