How to create Lambda Function using CloudFormation

This tutorial explains how to create AWS Lambda Function using CloudFormation template.

AWS Lambda Function using CloudFormation

Follow below steps to create Python Lambda function using CloudFormation template.

Step 1: Create directory with name cft-tutorials and open it in vscode.

Step 2: Create a file sample_cft.yaml inside cft-tutorials.

Step 3: Copy the below YAML template in sample_cft.yaml. Below CloudFormation template first creates an IAM Role with two managed policies AmazonS3ReadOnlyAccess and AWSLambdaBasicExecutionRole, and attaches IAM Role to the Lambda Function

   
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:      
      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
   

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

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

Step 6: 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

Step 7: Enter Stack name and click on Next.

cft-iam-role

Step 8: In "Configure stack options" page click on Next.

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

cft-iam-role

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

cft-iam-role

CFT template for connecting Lambda to VPC

   
  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
     

Category: AWS