How to create Lambda Function using CloudFormation

This tutorial explains how to create AWS Lambda Function using CloudFormation template. This post provides example CFT templates to create a lambda function with VPC connectivity and without VPC connectivity.

See Also

AWS Lambda Function using CFT

Let's follow below steps to create Python Lambda function using CFT template.

1: Create a file sample_cft.yaml inside.

2: Copy the below YAML template in sample_cft.yaml.

AWS Lambda CFT template

   
AWSTemplateFormatVersion: '2010-09-09'
Resources:
  TestLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: test-lambda-role
      Description: "IAM role for TestLambdaFunction."
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  TestLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: test-lambda-function   
      Role: !GetAtt TestLambdaRole.Arn
      Handler: index.handler
      Code:
        ZipFile: |
          import json

          def lambda_handler(event, context):
              print("hello world")
      Description: Invoke a function during stack creation.
      Runtime: python3.9
      Timeout: 15
      MemorySize: 128
   

The above template will deploy following resources.

  • TestLambdaRole: IAM role with name test-lambda-role that will be used as lambda execution role.
  • TestLambdaFunction: Lambda function with name test-lambda-function.

3: Open the AWS CloudFormation directly with the URL https://console.aws.amazon.com/cloudformation/ .

4: Navigate to Stacks, Click on Create stack and click on With new resources (standard).

5: Select Template is ready . Select Upload a template file. Click on Choose file to select sample_cft.yaml from cft-tutorials directory and click on Next.

cft-iam-role

6: Enter Stack name and click on Next.

cft-iam-role

7: In "Configure stack options" page click on Next.

8: Scroll down to check the confirmation for creating IAM roles and click on Create stack.

cft-iam-role

9: Check Stack Events section, on completion you should see CREATE_COMPLETE for the stack.

cft-iam-role

AWS Lambda CFT template with VPC

In the previous section we created lambda without VPC connectivity, lets deploy the lambda function with VPC connectivity.

   
  AWSTemplateFormatVersion: '2010-09-09'
  Resources:
    LambdaExecutionRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: lambda-execution-role
        Description: "IAM role for VPCLambdaFunction."
        AssumeRolePolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action:
                - 'sts:AssumeRole'
        ManagedPolicyArns:
          - arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
          - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
  
    VPCLambdaFunction:
      Type: AWS::Lambda::Function
      Properties:      
        Role: !GetAtt LambdaExecutionRole.Arn
        Handler: index.handler
        Code:
          ZipFile: |
            import json
  
            def lambda_handler(event, context):
                print("hello world")
        Description: Lambda function configured to connect to VPC.
        Runtime: python3.9
        Timeout: 15
        VpcConfig:
          SecurityGroupIds:
            - sg-085912345678492fb # Replace with your security group id
          SubnetIds:
            - subnet-071f712345678e7c8 # Replace with your subnet id
            - subnet-07fd123456788a036 # Replace with your subnet id
        MemorySize: 128
     

In the above cft template VpcConfig property specifies security groups and subnets for the lambda function.


Category: AWS