Reputation: 2050
Goal:
serverless.yml
file and in the code also.serverless.yml
also.Solution:
I try to use the environment variable in serverless.yml
file in the following way:
provider:
name: aws
runtime: java11
stage: dev
region: us-east-1
environment:
DYNAMO_DB_TABLE: "tableName"
......
resources:
Resources:
S3ObjectsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: ${DYNAMO_DB_TABLE} /solution1
TableName: ${env:DYNAMO_DB_TABLE} /solution2
............
With solution1 I receive an error: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+
In the documentation, I found several tips, but nothing worked for me, for example:
service: new-service
provider: aws
functions:
hello:
name: ${env:FUNC_PREFIX}-hello
handler: handler.hello
world:
name: ${env:FUNC_PREFIX}-world
handler: handler.world
For my case (solution2) I receive error: Value not found at "env" source
I also tried to create variables in env.yml
with useDotenv: true
parameter in serverless.yml
and other and other else, but nothing works for me.
How to correctly create and use environment variables in serverless.yml
?
Upvotes: 2
Views: 5344
Reputation: 2050
That solution works for me:
I created .env
file where I set the needed variables:
DYNAMO_DB_TABLE=s3ObjectsTable
S3_BUCKET_NAME=test-task-files
In this case, I can use them in the serverless.yml
and in the project:
service: serverless-task
frameworkVersion: '3'
useDotenv: true
provider:
name: aws
runtime: java11
stage: dev
region: us-east-1
environment:
DYNAMO_DB_TABLE: ${env:DYNAMO_DB_TABLE}
....
enter code here
resources:
Resources:
S3Bucket:
DeletionPolicy: Retain
Type: AWS::S3::Bucket
Properties:
BucketName: ${env:S3_BUCKET_NAME}
From the code:
public static String DYNAMO_DB_TABLE_NAME = System.getenv("DYNAMO_DB_TABLE");
Upvotes: 3
Reputation: 31
You have two possibilities to use dotenv, using this plugin serverless-dotenv-plugin. When you use serverless version 3, you can use dotenv=true
Upvotes: 1