How to Create a Lambda in CloudFormation


You can create a Lambda in CloudFormation as follows:

Option 1 - Inline code

Resources:
  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: MyLambdaFunction
      Runtime: python3.8
      Handler: index.lambda_handler
      Code:
        ZipFile: |
          import json

          def lambda_handler(event, context):
              # Your Lambda function code here
              return {
                  'statusCode': 200,
                  'body': json.dumps('Hello from Lambda!')
              }          
      Role: !GetAtt MyLambdaExecutionRole.Arn

In this example, instead of specifying the S3Bucket and 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 S3Bucket and S3Key properties.

Option 2 - Include a Zip file of code

Resources:
  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: MyLambdaFunction
      Runtime: python3.8
      Handler: index.lambda_handler
      Code:
        S3Bucket: my-lambda-bucket
        S3Key: lambda-code.zip
      Role: !GetAtt MyLambdaExecutionRole.Arn

Let’s break down the example:

  1. Resources: This section defines the resources you want to create. In this case, you’re creating a Lambda function named MyLambdaFunction.

  2. Type: AWS::Lambda::Function: This specifies that you want to create a Lambda function resource.

  3. 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.