Create a Lambda function using AWS CloudFormation with Python code
I have been working as a DevOps engineer @TESCRA for an Airlines Client. Mainly on Platform Engineering and Application logging and monitoring end
What is CloudFormation in AWS
AWS CloudFormation is a service that gives developers and businesses an easy way to create a collection of re lated AWS and third-party resources, and provision and manage them in an orderly and predictable fashion.
Create a Lambda function
To create a Lambda function using AWS CloudFormation with Python code, you need to define the Lambda function resource within your CloudFormation template. Here’s a step-by-step example of how to do this:
CFN stack
Below is a CloudFormation template in YAML format that defines a Lambda function written in Python hello message
AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template for a Lambda function
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.8
Timeout: 30
MemorySize: 128
Code:
ZipFile: |
import json
def lambda_handler(event, context):
print("Hello from Lambda!")
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
AWSTemplateFormatVersion: Specifies the AWS CloudFormation template version.
Description: Provides a description of the CloudFormation template.
Resources: Defines the AWS resources to be created or managed by this CloudFormation stack.
MyLambdaFunction: Defines a Lambda function resource.
Type: Specifies the AWS resource type (
AWS::Lambda::Function).Properties: Specifies the configuration properties for the Lambda function.
Handler: Specifies the name of the Lambda function handler. Here,
lambda_functionrefers to the Python file (lambda_function.py) andlambda_handleris the function inside that file that will be invoked.Runtime: Specifies the runtime environment for the Lambda function. Here, it's set to
python3.8.Timeout: Specifies the function execution timeout in seconds.
MemorySize: Specifies the amount of memory in MB allocated to the Lambda function.
Code: Specifies the function code. In this example,
ZipFilecontains the Python code for the Lambda function.
Deploying the CloudFormation Template:
aws cloudformation create-stack --stack-name MyLambdaStack --template-body file://lambda-template.yaml --capabilities CAPABILITY_IAM
Run or Invoke lambda function
aws lambda invoke --function-name MyLambdaFunction output.txt



