aws cloudformation creating lamda
First of all we need to run the following scripts to create our lambda function in python/
AWSTemplateFormatVersion: '2010-09-09'
Description: 'AWS Lambda Function with IAM Role and Log Group'
Resources:
# 1. IAM Role for Lambda Execution
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: [lambda.amazonaws.com]
Action: ['sts:AssumeRole']
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# 2. CloudWatch Log Group (Prevents logs from being kept forever)
LambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/MyCloudFormationFunction"
RetentionInDays: 7
# 3. The Lambda Function
MyLambdaFunction:
Type: AWS::Lambda::Function
DependsOn: LambdaLogGroup
Properties:
FunctionName: "MyCloudFormationFunction"
Handler: index.lambda_handler
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.12
Architectures:
- arm64 # Modern Graviton architecture (cheaper/faster)
Timeout: 10
MemorySize: 128
Code:
ZipFile: |
import json
def lambda_handler(event, context):
print("Hello from CloudFormation!")
return {
'statusCode': 200,
'body': json.dumps('Hello from the Cloud!')
}
Outputs:
LambdaArn:
Value: !GetAtt MyLambdaFunction.Arn
And then we can run the following cli command to deploy this stack
aws cloudformation create-stack \
--stack-name my-lambda-stack \
--template-body file://lambda.yaml \
--capabilities CAPABILITY_IAM \
--region ap-southeast-2
Comments