Function start instance

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

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

Lambda Function start instance

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

Lambda Function start instance

  1. 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

Lambda Function start instance

  1. Trước khi import code , hãy tạo Environment variables như sau:
  • Chọn Configuration
  • Chọn Environment variables
  • Chọn Edit

Lambda Function start instance

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

Lambda Function start instance

  1. Sau khi tạo môi trường
  • Chọn Code
  • 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 logging
import urllib3

logger = logging.getLogger()
logger.setLevel(logging.INFO)

ec2_resource = boto3.resource('ec2')
http = urllib3.PoolManager()
webhook_url = "https://hooks.slack.com/services/XXXXX/XXXXX/XXXXX"  # Thay bằng Webhook URL của bạn

def lambda_handler(event, context):
    environment_auto = os.environ.get('environment_auto')
    if not environment_auto:
        logger.info('Target is empty')
        return {
            "statusCode": 400,
            "body": "Environment variable 'environment_auto' is not set"
        }

    instances = ec2_resource.instances.filter(
        Filters=[{'Name': 'tag:environment_auto', 'Values': [environment_auto]}]
    )

    instance_list = list(instances)
    if not instance_list:
        return {
            "statusCode": 500,
            "body": "Target Instance is None"
        }

    action_start = instances.start()
    send_slack(action_start)
    return {
        "statusCode": 200,
        "body": "EC2 Starting"
    }


def send_slack(action_start):
    list_instance_id = []
    if (
        len(action_start) > 0
        and "StartingInstances" in action_start[0]
        and len(action_start[0]["StartingInstances"]) > 0
    ):
        for instance in action_start[0]["StartingInstances"]:
            list_instance_id.append(instance["InstanceId"])

        msg = f"Starting Instances ID:\n {list_instance_id}"
        data = {"text": msg}
        http.request(
            "POST",
            webhook_url,
            body=json.dumps(data).encode("utf-8"),
            headers={"Content-Type": "application/json"}
        )
    else:
        logger.info('Not found Instances Start')
  • Lưu lại và chọn Deploy

Lambda Function start instance

  1. Tiếp theo tạo schedule trên EventBridge Scheduler
  • Truy cập Amazon EventBridge
  • Ở menu bên trái, chọn Schedules (hoặc Scheduler > Schedules)
  • Chọn Create schedule Lambda Function start instance
  1. Trong Step 1: Specify schedule detail
  • Schedule name: nhập dc-common-lambda-auto-start
  • Description: nhập dc-common-lambda-auto-start
  • Trong phần Schedule pattern:
    • Chọn Recurring schedule
    • Schedule type: chọn Rate-based schedule
    • Rate expression: nhập 8 và đơn vị chọn hours
    • Phần Flexible time window: chọn Off
  • Chọn Next

Lambda Function start instance Lambda Function start instance

  1. Trong Step 2: Select target
  • Trong danh sách các target, chọn AWS Lambda (hoặc tìm Lambda Invoke)
  • Lambda function: chọn function dc-common-lambda-auto-start
  • Chọn Next Lambda Function start instance
  1. Trong Step 3: Settings
  • Giữ các cấu hình mặc định (Execution role, Retry policy…)
  • Chọn Next

Lambda Function start instance

  1. Trong Step 4: Review and create schedule
  • Kiểm tra lại toàn bộ thông tin
  • Chọn Create schedule để hoàn tất việc lập lịch tự động chạy Lambda Function khởi động EC2 instance. Lambda Function start instance