Search code examples
aws-lambdaaws-serverlessaws-samaws-sam-cli

SAM build in container with environment variables


Is there a way to pass environment variables to the container doing the build in:

sam build --use-container

In the sam build documentation, in parameters related to Docker, there is only --docker-network and --skip-pull-image

Use case:

I am using private PyPI repository, and I need to pass credentials as environment variables.

Workaround:

A workaround is:

  • Pull the docker image used by sam, e.g. lambci/lambda:build-python3.7
  • Build a new image with same name & tag
  • Run sam build -u with parameter --skip-pull-image

Update 1:

Created a feature request in SAM repo: https://github.com/aws/aws-sam-cli/issues/2144

Update 2:

New parameters were released: --container-env-var and --container-env-var-file in v1.20.0


Solution

  • Starting from release v1.20.0 (2021-03-04) you can pass environment variables to the container, either from the command line:

    sam build --use-container \
        --container-env-var Function1.GITHUB_TOKEN=<token1> \
        --container-env-var GLOBAL_ENV_VAR=<global-token>
    

    or from a file:

    sam build --use-container --container-env-var-file <env-file.json>
    

    Ref: sam build documentation