Function start instance

Create Lambda Function to start instances

  1. In the Lambda Function interface
  • Select Create function

Lambda Function start instance

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

Lambda Function start instance

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

Lambda Function start instance

  1. Before importing the code, create the following Environment variables:
  • Select Configuration
  • Select Environment variables
  • Select Edit

Lambda Function start instance

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

Lambda Function start instance

  1. After creating the environment
  • Select Code
  • 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_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')
  • Save and select Deploy

Lambda Function start instance

  1. Next, create a schedule on EventBridge Scheduler
  • Access Amazon EventBridge
  • In the left menu, select Schedules (or Scheduler > Schedules)
  • Select Create schedule Lambda Function start instance
  1. In Step 1: Specify schedule detail
  • Schedule name: enter dc-common-lambda-auto-start
  • Description: enter dc-common-lambda-auto-start
  • In the Schedule pattern section:
    • Select Recurring schedule
    • Schedule type: select Rate-based schedule
    • Rate expression: enter 8 and select hours for the unit
    • For Flexible time window: select Off
  • Select Next

Lambda Function start instance Lambda Function start instance

  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-start function
  • Select Next Lambda Function start instance
  1. In Step 3: Settings
  • Keep the default settings (Execution role, Retry policy…)
  • Select Next

Lambda Function start instance

  1. In Step 4: Review and create schedule
  • Review all information
  • Select Create schedule to complete scheduling the Lambda Function to start EC2 instances automatically. Lambda Function start instance