How to provide global environment variables to AWS SAM local
Asked Answered
S

2

7

When running sams locally to test my api gateway and passing environment variables, I can run the command

sam local start-api -n env-vars.json

This works well when the environment variables are tied to a specific function like this

MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    Handler: index.handler
    Runtime: nodejs8.10
    CodeUri: .
    Environment:
      Variables:
        FIRST_BUCKET: !Ref firstBucket
        SECOND_BUCKET: !Ref secondBucket

However, I currently have global enviroment variables like this

Globals:
  Function:
    CodeUri: .
    Runtime: nodejs8.10
    Environment:
      Variables:
        FIRST_BUCKET: !Ref firstBucket
        SECOND_BUCKET: !Ref secondBucket

How can I pass custom global environment variables to SAMS using env-var.json? I'd expect to be able to do something like this for my env-var.json file

{
  "Globals": {
    "Function": {
      "FIRST_BUCKET": "this-is-my-bucket-name"
    }
  }
}

Unfortunately, this does not work and I can not find any resources online showing the correct syntax to achieve this behavior.

Spunk answered 2/5, 2019 at 18:37 Comment(0)
W
0

I will have to test this tomorrow, but reading through the transform documentation (and what I understand of the SAM transform) I expect the global variables are just applied to each function without having to re-state them.

So you will form your env.json as normal for each function: e.g.,

{
  "MyFunction": {
      "FIRST_BUCKET": "this-is-my-bucket-name"
  },
  "MySecondFunction": {
      "SECOND_BUCKET": "this-is-my-second-bucket-name"
  }
}

This will result in your lambda functions having both globals, but only overwriting the passed value:

MyFunction:

  • FIRST_BUCKET = "this-is-my-bucket-name"
  • SECOND_BUCKET = !Ref secondBucket

MySecondFunction:

  • FIRST_BUCKET = !Ref firstBucket
  • SECOND_BUCKET = "this-is-my-second-bucket-name"

Remember, your function will have both variables used in your function, but you are only overwriting the variable you are passing from json.

Wilke answered 9/9, 2019 at 4:27 Comment(0)
B
0

I stumbled about this issue today, and luckily I found this blog posts, which worked for me.

https://whatibroke.com/2019/01/15/overriding-global-variables-aws-sam-local/

In your case it should be the following

{
    "Parameters": {
        "FIRST_BUCKET": "this-is-my-bucket-name"
    }
}

Afterward, you can test it with

sam local start-api --env-vars env-vars.json
Bor answered 28/5 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.