r/aws•
jQueryBoi

[SAM] How to use environment variables locally and Parameter Store when deploying?

technical question

I'm having trouble with this SAM thing. I want to provide my Lambda function with some variables from the environment.

The docs say you should use Parameter Store or Secrets Manager. Ok, fine I set that up.

But when testing locally, I just want to pass those variables to my function without having to setup Parameter Store. How do I do that?

For reference, here is my template.yml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  helloworld

  Sample SAM Template for helloworld

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 120
    MemorySize: 1024

Parameters:

    DDBTableName:
        Description: 'DynamoDB table name'
        Type: AWS::SSM::Parameter::Value<String>

    DebugMode:
      Description: "Run in debug mode"
      Type: AWS::SSM::Parameter::Value<String>

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.11
      Architectures:
        - x86_64
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref DDBTableName
      Environment:
        Variables:
          DDB_TABLE_NAME: !ref DDBTableName
          DEBUG: !ref DebugMode
      Events:
        ApiRoot:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /
            Method: any
        ApiProxy:
          Type: Api
          Properties:
            Path: /{proxy+}
            Method: any
Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

I'm setting up 2 parameters:

  1. DDBTableName
  2. DebugMode

They map to DDB_TABLE_NAME and DEBUG respectively.

In my local environment, is there a way to pass DDB_TABLE_NAME directly without having to fetch it from Parameter Store?

Posted Sep 2, 2023, 4:39 PM UTC

12
ManReally•

If it's not sensitive data lambda have local environment variables you could maybe use.

1
jQueryBoiOP•

That's the problem, I'm trying to figure out how to pass environment variables without adding them to the template.yml file because I'll be committing this to git.

However, I want to use Parameter Store because I'll have api keys and stuff that I want my function to use as well. But I want to pass those api keys directly as environment variables while developing locally.

It's a simple task but the docs are huge and I can't find how to do it.

I asked chatgpt but it provided me with a solution that seems correct but doesn't work. It told me to use this temnplate:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  helloworld

  Sample SAM Template for helloworld

Globals:
  Function:
    Timeout: 120
    MemorySize: 1024

Parameters:
  DDBTableName:
    Description: 'DynamoDB table name'
    Type: String  # Change the parameter type to String

  DebugMode:
    Description: "Run in debug mode"
    Type: String  # Change the parameter type to String

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.11
      Architectures:
        - x86_64
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !If [IsLocal, !Ref DDBTableNameLocal, !Ref DDBTableName]  # Conditionally use local or AWS parameter
      Environment:
        Variables:
          DDB_TABLE_NAME: !If [IsLocal, !Ref DDBTableNameLocal, !Ref DDBTableName]  # Conditionally use local or AWS parameter
          DEBUG: !If [IsLocal, !Ref DebugModeLocal, !Ref DebugMode]  # Conditionally use local or AWS parameter

  # ...

Conditions:
  IsLocal: !Equals [ !Ref AWS::Region, "local" ]

Outputs:
  # ...

And to add my parameters to local-parameters.yml:

Parameters:
  DDBTableName: "mytable"
  DebugMode: "1"

And run the command:

sam local start-api --parameter-overrides $(cat local-parameters.yml | jq -r 'to_entries[] | "\(.key)=\(.value)"')

But the answer is incomplete. I wonder if gpt4 could get it right.

1
diogoko•

I see you decided to use two different template.yml files, but for future reference, this is how you can override the env vars.

I add my vars to local-parameters.json:

{
  "Parameters": {
    "DDB_TABLE_NAME": "mytable",
    "DEBUG": "1"
  }
}

Then use the file with the -n/--env-vars parameter:

sam local start-api -n local-parameters.json ...

In the template, there's no need to use that "If IsLocal" trick.

1