Function stop instance

Create Lambda Function to stop instances

  1. Access AWS Management Console
  • Find Lambda
  • Select Lambda

Create Lambda Function for Stop instance

  1. In the AWS Lambda interface
  • Select Functions
  • 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.14

Create Lambda Function for Stop instance

  1. Continue in the 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 the function is created 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 the environment is created successfully
  • Select Code

Create Lambda Function for Stop instance

  1. In the Code source interface
  • Import source code: You need to change the webhook_url to receive notifications to 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"  # Replace with your Webhook URL

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_stop = instances.stop()
    send_slack(action_stop)
    return {
        "statusCode": 200,
        "body": "EC2 Stopping"
    }


def send_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 instance in action_stop[0]["StoppingInstances"]:
            list_instance_id.append(instance["InstanceId"])

        msg = f"Stopping 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 Stop')

Create Lambda Function for Stop instance

  1. Save and select Deploy

Create Lambda Function for Stop instance

  1. Access AWS Management Console
  • Find EventBridge
  • Select Amazon EventBridge

Access EventBridge

  1. In the Amazon EventBridge interface
  • In the left navigation menu, select Schedules (or Scheduler > Schedules)
  • Select Create schedule Create schedule
  1. In Step 1: Specify schedule detail
  • Schedule name: enter dc-common-lambda-auto-stop
  • Description: enter dc-common-lambda-auto-stop
  • In the Schedule pattern section:
    • Select Recurring schedule
    • Schedule type: select Rate-based schedule
    • Rate expression: enter 9 and select hours for the unit (or choose a desired interval)
    • For Flexible time window: select Off
  • Select Next Create schedule Create schedule
  1. In Step 2: Select target
  • From the list of targets, select AWS Lambda (or search for Lambda Invoke)
  • Lambda function: select the dc-common-lambda-auto-stop function created in previous steps
  • Select Next Create schedule
  1. In Step 3: Settings
  • Keep the default settings (Execution role, Retry policy…)
  • Select Next Create schedule
  1. In Step 4: Review and create schedule
  • Review all information
  • Select Create schedule to complete scheduling the Lambda Function to stop EC2 instances automatically. Create schedule