Is it possible to access the env variables inside lambda functions with amplify?
Here is an list with available env variables:
https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html
From this list i need for example AWS_BRANCH. How do i access it inside the function?
I tried with process.env.AWS_BRANCH
but its undefined.
2
Answers
I have found an workaround. I do it with the hooks: https://docs.amplify.aws/cli/project/command-hooks/
Here i use the
pre-push.js
hook that gets executed before the build.Here is how i inject the environment variable
AWS_BRANCH
into my lambda:First i need to read it:
Then i edit it:
Now i write the file back:
This actually works. Now i can access
process.env.AWS_BRANCH
inside my lambdaThere may be a better way than what I describe.
This comment uses
jq
to inject the build environment variable directly into your cloud formation.You can put key-value pairs into the
parameters.json
file that sits next to the Lambda’sxxxxxx-cloudformation-template.json
file to inject the AWS_BRANCH value. e.g.You’d need to inject that into the build script, perhaps via
amplify.yml
.Second approach
You could modify the above to update an existing key in the
parameters.json
file. That will add it to your cloudformation and you can pull it into the resources environment vars. That seems a bit cleaner:parameters.json
But then you still need to augment the build to inject the variable. The "best" way (until you find a better way) in my opinion would be to hard-code the value into each "environment" (e.g.
dev
,prod
) in theamplify/team-provider-info.json
file. Add it to the resources that need it and the value will be exposed to CloudFormation. Next, update the Lambda’s CloudFormation and add it to the parameters and lambda environment vars.Update your
xxxxx-cloudformation-template.json
file to have the property.Then in the lambda resource, convert the parameter to an environment var:
And then in your typescript code you can just access the parameter
process.env.AWS_BRANCH
.