hrushilok
hrushilok

Reputation: 455

create lambda using .env file

I have four lambda to be created. my folder structure is as below

folder1ForLambda1
  index.js
  package.json
  .env
folder2ForLambda2
  index.js
  package.json
  .env
folder3ForLambda3
  index.js
  package.json
  .env
folder4ForLambda4
  index.js
  package.json
  .env
build.sh

I have build script for all the lambdas in build.sh file. I would like to use respective .env file to set environment variables for each lambda.

pushd ./folder1ForLambda1
aws lambda create-function \
  --function-name $PREFIX-$MODULE_NAME \
  --runtime nodejs6.10 \
  --handler "index.handler" \
  --code S3Bucket=$BUCKET_NAME,S3Key=$ZIP_NAME.zip \
  --environment Variables="" \
  --memory-size 512 \
  --timeout 5 \
  --publish
popd

I have this code for each lambda. How do I use .env to set environment variables?

Upvotes: 1

Views: 2328

Answers (2)

Larry K
Larry K

Reputation: 49104

aws lambda create-function accepts --environment option. But update-function-code does not.

Instead, use update-function-configuration to create/update environment variables.

This command chain (below) handles .env files that include comment lines and values that include blanks.

Input:

# this is a comment 
ABC=1
DEF="A blank is included"

Command line:

aws lambda update-function-configuration \
--function-name API_Request_Builder_Gateway \
--environment Variables="{`cat .env | sed '/^#/d' | \
sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/,/g'`}"

sed tip: SO answer

Upvotes: 0

Samir Aleido
Samir Aleido

Reputation: 1046

You can use source to read environment variables from a file (.env in your case)

source ./folder1ForLambda1/.env

Update

Try this:

--environment Variables="{`cat .env | xargs | sed 's/ /,/g'`}" \
  • Using cat to feed xargs
  • Using xargs to get the variables from stdin, output looks like k1=v11 k2=v33
  • Using sed to replace spaces with commas separate variables k1=v11 k2=v33

So your script will look like

pushd ./folder1ForLambda1
aws lambda create-function \
--function-name $PREFIX-$MODULE_NAME \
--runtime nodejs6.10 \
--handler "index.handler" \
--code S3Bucket=$BUCKET_NAME,S3Key=$ZIP_NAME.zip \
--environment Variables="{`cat .env | xargs | sed 's/ /,/g'`}" \
--memory-size 512 \
--timeout 5 \
--publish
popd

Upvotes: 1

Related Questions