Using Serverless Framework ${file()}
variable to load external files into serverless.yml
.
service: serverless-framework-include-files
frameworkVersion: "3"
provider: ${file(config/provider.yml):provider}
functions:
function1:
handler: index.handler
resources:
- ${file(resources/s3-bucket.yml)}
- ${file(resources/dynamodb-table.yml)}
- The variable
${file(...):<key-name>}
use thekey-name
as the property key in the external file to be included in theserverless.yml
file. Make sure the key name exists in the external file with a colon<key-name>:
. In this example we are looking for theprovider
key in theconfig/provider.yml
file:
provider: # <--- key name, it will load the properties of the key name as configuration
name: aws
runtime: nodejs14.x
- You can include the whole file by removing the key name:
${file(...)}
. Make sure the external file contains the correct configuration for target property in theserverless.yml
file.
# no key name, it will load the whole file as configuration values in the serverless.yml file
name: aws
runtime: nodejs14.x
The serverless.yml
file supports multiple ways to declare AWS resources. These resources use the CloudFormation Resources syntax.
resources:
Resources:
# <--- Declare any AWS resources here
You can declare AWS resources inline, include external files with the resources configuration or use the array syntax to mix inline and external files.
resources:
Resources:
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-bucket
MyTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: my-table
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
Make sure the contents of your external file match the configuration of the AWS resource.
resources:
Resources:
MyBucket: ${file(resources/s3-bucket2.yml)}
MyTable: ${file(resources/dynamodb-table2.yml)}
The resources/s3-bucket2.yml
file:
Type: AWS::S3::Bucket
Properties:
BucketName: my-bucket
AccessControl: PublicRead
WebsiteConfiguration:
IndexDocument: index.html
ErrorDocument: error.html
Make sure your external files are declaring/start with the Resources:
key.
resources:
- ${file(resources/s3-bucket.yml)}
- ${file(resources/dynamodb-table.yml)}
The resources/s3-bucket2.yml
file:
Resources: # <--- required CloudFormation syntax
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-bucket
AccessControl: PublicRead
WebsiteConfiguration:
IndexDocument: index.html
ErrorDocument: error.html
The secret sauce is the Resources:
key. It allows you to mix inline and external files.
resources:
- ${file(resources/s3-bucket.yml)}
- Resources:
MyBucket: ${file(resources/s3-bucket2.yml)}
- Resources:
MyTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: ${self:service}
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1