I create AWS lambda using container image. However the environment variables defined in YAML is not found.
How I create the container image
AWS Quick Start Templates
> Hello World Example
template.yaml
with environment variablessam build
Here is the YAML I tried
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
python3.9
Sample SAM Template for sam_hello_world
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Environment:
Variables:
BUCKET_NAME: "somes3bucketname"
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:
PackageType: Image
Architectures:
- x86_64
Metadata:
Dockerfile: Dockerfile
DockerContext: ./hello_world
DockerTag: python3.9-v1
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
python3.9
Sample SAM Template for sam_hello_world
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
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:
PackageType: Image
Architectures:
- x86_64
Environment:
Variables:
BUCKET_NAME: "somes3bucketname"
Metadata:
Dockerfile: Dockerfile
DockerContext: ./hello_world
DockerTag: python3.9-v1
My app.py
import io
import json
import os
def lambda_handler(event, context):
print(os.environ)
print(os.environ["BUCKET_NAME"])
return {"statusCode": 200}
However, this will throw keyerror because the environment variable is not found by os.environ.
{
"errorMessage": "'BUCKET_NAME'",
"errorType": "KeyError",
"requestId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"stackTrace": [
" File \"/var/task/app.py\", line 32, in lambda_handler\n os.environ[\"BUCKET_NAME\"],\n",
" File \"/var/lang/lib/python3.9/os.py\", line 679, in __getitem__\n raise KeyError(key) from None\n"
]
}
I suspect my steps from 3 onwards is wrong.
Basically, when sam build
is executed, it builds the container image, but the environment variables are not added into the image itself.
The only time the template.yaml
is taken into consideration is when you do sam deploy
.