Search code examples
mongodbaws-lambdasam

How can I use parameter to replace a mongodb connection string in a lambda function in AWS SAM?


In my amplify lambda backend project, template.yaml file mentioned connection string for mongodb connection for all lambda functions respectively like below example.

Resources:
  authenticateFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/member/authenticateMember.authenticateMemberHandler
      Runtime: nodejs18.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP post method to add one item to a DynamoDB table.
      Environment:
        Variables:
          CONNECTION_STRING: mongodb+srv://xxx:[email protected]/?retryWrites=true&w=majority
      Events:
        Api:
          Type: Api
          Properties:
            Path: /member/authenticate
            Method: POST

I want to replace the above one with the other one like below using paramater. I need your assist to correct the below snippet of template.yaml?

Parameters:
  ConnectionString:
    Type: 'AWS::SSM::Parameter::Value<String>'
    Description: Enter SSM key for the mongodsb connection string, including user name and password

Transform:
  - AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 20
  Api:
    Cors:
      AllowMethods: "'GET,POST,PUT,OPTIONS'"
      AllowHeaders: "'content-type'"
      AllowOrigin: "'*'"
      AllowCredentials: "'*'"

Resources:
  authenticateFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/member/authenticateMember.authenticateMemberHandler
      Runtime: nodejs18.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP post method to add one item to a DynamoDB table.
      Environment:
        Variables:
          CONNECTION_STRING: !Ref ConnectionString
      Events:
        Api:
          Type: Api
          Properties:
            Path: /member/authenticate
            Method: POST

Can someone help me with this?


Solution

  • Parameters:
      ConnectionString:
        Type: 'AWS::SSM::Parameter::Value<String>'
        Description: Enter SSM key for the mongodsb connection string, including user name and password
        Default: mongodb+srv://xxx:[email protected]/?retryWrites=true&w=majority
    

    Please try with this configuration. You can replace the temp string of "Default" with your correct connection string.

    And double check for all resources whether they have "CONNECTION_STRING: !Ref ConnectionString" inside.

    Hope this answer help you.