Member-only story

AWS Lambda function that can start or stop an EC2 instance.

Infrastructure provided with Terraform

Alex
4 min readApr 11, 2025

This project contains an AWS Lambda function that can start or stop an EC2 instance (or many) at a specified time. It utilizes the AWS SDK for Python (Boto3) to interact with AWS services and Terraform for infrastructure management.

The diagram was also created with code. Take a look.

# Import necessary libraries
import boto3 # AWS SDK for Python to interact with AWS services
import os # For accessing environment variables
from datetime import datetime # For working with date and time
import pytz # For handling time zones

# Initialize the EC2 client
ec2 = boto3.client('ec2')

# Lambda function entry point
def lambda_handler(event, context):
# Retrieve the action ('start' or 'stop') from the event
action = event.get('action')

# Retrieve the EC2 instance ID from environment variables
instance_id = os.environ.get('INSTANCE_ID')

# Retrieve the timezone from environment variables, default to 'UTC'
timezone = os.environ.get('TIMEZONE', 'UTC')

# Get the current time in the specified timezone and format it as HH:MM
current_time = datetime.now(pytz.timezone(timezone)).strftime('%H:%M')

# Allow overriding the current time for testing purposes
test_time = event.get('test_time') #…

--

--

Alex
Alex

Written by Alex

DevOps Lead @evinova, former Dynatrace Solutions Engineer. Cheerleader in Chief for KMMX, Technical Writer & International Speaker, Dad & 2 cats.

No responses yet