How to configure Lambda function to connect to VPC

This tutorial explains how to configure an AWS Lambda function to connect to private subnets in a VPC using CloudFormation template.

Lambda function configuration with VPC

Below are the steps to create a Lambda function and to configure it to connect to VPC 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 AWSLambdaVPCAccessExecutionRole and AWSLambdaBasicExecutionRole, and attaches IAM Role to the Lambda Function. In the below template replace SecurityGroupIds and SubnetIds with proper values.

   
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
   

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


Follow US on Twitter:

Category: AWS

Similar Articles