Automating EC2 with AWS Lambda Using Boto3- Lab 1

Shivani Singh
2 min readNov 26, 2023

Problem statement:
Develop an AWS Lambda function to automate the provisioning of Amazon Elastic Compute Cloud (EC2) instances based on specific configurations. The function should be triggered on demand and utilize environment variables to dynamically set parameters such as the Amazon Machine Image (AMI) ID, instance type, key name, and subnet ID. Upon execution, the Lambda function should create a single EC2 instance with the provided specifications and print the unique identifier (ID) of the newly created instance to the console. This solution aims to streamline the process of launching EC2 instances with predefined settings, facilitating the deployment of resources in an efficient and automated manner.

Use case:
Create an EC2 instance using lambda and boto3.

#importing os which is used to access environment variables, 
# and boto3 is the AWS SDK for Python, which provides
#a Python interface to AWS services.

import os
import boto3

#Environment Variables:
#The code uses os.environ to retrieve values from environment variables.
#AMI, INSTANCE_TYPE, KEY_NAME, and SUBNET_ID are environment variables
#that should be set in the Lambda function configuration

AMI = os.environ['AMI']
INSTANCE_TYPE = os.environ['INSTANCE_TYPE']
KEY_NAME = os.environ['KEY_NAME']
SUBNET_ID = os.environ['SUBNET_ID']


#This line creates an EC2 resource using boto3.resource('ec2').
#The ec2 variable is now an instance of the EC2 resource.

ec2 = boto3.resource('ec2')

#The lambda_handler function is the entry point for the Lambda function.
#It takes two parameters: event and context.

def lambda_handler(event, context):

instance = ec2.create_instances(
ImageId=AMI,
InstanceType=INSTANCE_TYPE,
KeyName=KEY_NAME,
SubnetId=SUBNET_ID,
MaxCount=1,
MinCount=1
)

#This line prints the ID of the newly created instance to
# the console. The instance ID is accessed using instance[0].id
print("New instance created:", instance[0].id)

Hope this was helpful!
Happy Learning
Shivani S

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shivani Singh
Shivani Singh

Written by Shivani Singh

DevOps Engineer, Passionate for new tools and Technology!

No responses yet

Write a response