Search code examples
node.jsamazon-web-servicesaws-lambdaserverless-frameworkaws-parameter-store

How to access SSM Parameter Store Values through AWS Lambda Function Environment Variables using Serverless Framework?


So I've configured my lambda function's .yaml file like so:

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: An AWS Serverless Specification template describing your function.
Resources:
  NewUser:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: NewUser/index.handler
      Runtime: nodejs8.10
      Environment:
        Variables:
          database_encrypt: ${ssm:databaseEncrypt}
          database_password: ${ssm:databasePassword}
          database_server: '8.8.8.8'
          database_user: ${ssm:databaseUser}
          database_version: ${ssm:databaseVersion}
      Description: ''
      MemorySize: 128
      Timeout: 15
      Role: 'arn:aws:iam::663404525923:role/LambdaRole'
      Events:
        LambdaMicroservice:
          Type: Api
          Properties:
            Path: /User/NewUser
            Method: ANY

and my lambda function looks like this:

var config = {  
  user: process.env.database_user,  
  password: process.env.database_password,  
  server: process.env.database_server,
  database: process.env.database_version,
  options: {encrypt: true}  
};

class UserService {

    constructor(){
        console.log(config);
        console.log("test test test");
        this.connectionPool = new sql.connect(config);
    }
}

and I can access the hard-coded database_server value just fine, but the ${ssm: [myParam] } command is interpreted as a string instead of following the path and accessing the value stored in SSM Parameter Store.

Most of the examples I see have long complicated paths to point to their SSM Params but as I am just trying to show that it is possible to access the SSM Params at all in this manner I'm trying to keep it as simple as possible. I am also assuming that the ${ssm: [] } command is just not escaping at all because I would expect an undefined value to be returned if no SSM Param was found at the defined path.


Solution

  • SAM is a superset of CloudFormation, so the CloudFormation commands should work

          Environment:
            Variables:
              database_encrypt: '{{resolve:ssm-secure:databaseEncrypt:1}}' 
              database_password: '{{resolve:ssm-secure:databasePassword:1}}' 
    

    see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html