You can create a Lambda in CloudFormation as follows:
Option 1 - Inline code
In this example, instead of specifying the
S3Key properties under the
Code section, you use the
ZipFile property to provide the actual code as a multiline string. The code is written in Python and includes a simple Lambda handler function.
Remember that there is a limit to the size of the CloudFormation template, so if your Lambda code is large or complex, it’s generally recommended to store it in an external location like an S3 bucket and reference it using the
Option 2 - Include a Zip file of code
Let’s break down the example:
Resources: This section defines the resources you want to create. In this case, you’re creating a Lambda function named
AWS::Lambda::Function: This specifies that you want to create a Lambda function resource.
Properties: Here, you define the properties of the Lambda function.
FunctionName: This sets the name of the Lambda function.
Runtime: Specify the runtime environment for your function. In this example, we’re using
python3.8, but you can choose a different runtime.
Handler: Set the name of the file and the function within the file that should be executed when the Lambda function is invoked.
Code: Specify the location of the code for your Lambda function. In this example, we’re using code stored in an S3 bucket.
Role: Provide the ARN (Amazon Resource Name) of an IAM role that grants necessary permissions to the Lambda function.
!GetAtt MyLambdaExecutionRole.Arn: This retrieves the ARN of an existing IAM role named
MyLambdaExecutionRole. You would need to define this IAM role separately in your CloudFormation template.
Make sure to adjust the values according to your requirements. Once you have defined this resource in your CloudFormation template, you can deploy the template to create the Lambda function using AWS CloudFormation.