somod-docs
Version:
Documentation for SOMOD
298 lines (239 loc) • 13.3 kB
Markdown
```YAML
title: Serverless template.yaml in SOMOD Module | SOMOD
meta:
description:
Learn about reusing Infrastructure as a Code (IaaC) in SOMOD's serverless template.yaml.
```
# SOMOD's `serverless/template.yaml` file
The developer creates the serverless resources in `/serverless/template.yaml`. The SOMOD build command will validate the `/serverless/template.yaml` and generate `/build/serverless/template.json`.
When preparing AWS SAM's `template.yaml`, The SOMOD prepare command combines templates from all dependency modules.
> There is a difference between `/serverless/template.yaml` and `/template.yaml`.
>
> - `/serverless/template.yaml` is created by the module developer and adheres to SOMOD's template anatomy.
> - Whereas `/template.yaml` is generated by SOMOD's prepare command to match the anatomy of AWS SAM's template.yaml.
## Anatomy of the serverless/template.yaml
SOMOD defines the anatomy of the `serverless/template.yaml` with reusability in focus.
SOMOD's `serverless/template.yaml` file closely follows the structure of an AWS SAM template file, which is described in the [Template Anatomy](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-template-anatomy.html) section of AWS SAM Documentation.
SOMOD's `serverless/template.yaml` is different from AWS SAM's specification in the following ways
- `serverless/template.yaml` contains only two sections, **Resources** and **Outputs**
- Contains special keywords in the template. These keywords are processed and replaced with appropriate values when SAM Template is prepared.
### Example
```yaml
# yaml-language-server: $schema=../node_modules/somod-schema/schemas/serverless-template/index.json
Resources:
MyFunction1: # Resource Logical Id
Type: AWS::Serverless::Function # Type of the resource
Properties:
# Properties of the Resource
Outputs:
my.function.name: # output is exported to this parameter
SOMOD::Ref: # a SOMOD keyword
resource: MyFunction1
```
> In the prepared SAM `template.yaml`, the resource logical ids must be unique.
>
> SOMOD Generates resource ids in SAM template using the following formula
>
> ```
> SAMResourceLogicalId = "r" + (1st 8 characters in the sha256 hash of the module name) + SOMODResourceLogicalId
> ```
### Keywords
Keywords help to pre-process the template before creating the final SAM template.yaml.
Along with [Common Keywords](/reference/main-concepts/yaml-processing), SOMOD defines the following keywords for serverless/template.yaml
- **SOMOD::DependsOn**
Replaces AWS Cloudformation DependsOn attribute
```yaml
Resources:
MyResource1:
Type: ValidResourceType
# SOMOD::DependsOn must be used only as a property of a Resource
SOMOD::DependsOn: # list of dependency {module, resource} tuplets
- module: my-module
resource: MyResource2
- resource: MyResourceInSameModule # module is optional, when not provided current module is considerred
Properties:
# ...
```
- **SOMOD::Extend**
In SOMOD, a module can extend a resource created in the dependency module to alter its properties
```yaml
Resources:
MyResource1:
Type: ValidResourceType
# SOMOD::Extend must be used only as a property of a Resource
SOMOD::Extend: # This resource is not included in prepared template, instead its properties are merged with the original resource
module: my-module
resource: MyResource2
rules: # Optional Rules which hints the merging of properties in extended resource, see https://www.npmjs.com/package/json-object-merge
"$..items": APPEND
"$.cart.items": REPLACE
Properties:
# ...
```
> The resource having `SOMOD::Extend` keyword can not have any of `SOMOD::Access`, `SOMOD::DependsOn`, `SOMOD::Output`, or `SOMOD::CreateIf` keyword.
- **SOMOD::Output**
Each Resource in the AWS SAM template specification has some return values. Other resources can refer to these return values. `SOMOD::Output` restricts which of the return values are to be referred to.
```yaml
Resources:
MyResource1:
Type: ValidResourceType
# SOMOD::Output must be used only as a property of a Resource
SOMOD::Output: # If omitted completely, the default return value can be referred
default: true # if true, default return value can be referred
attributes: [] # list of attributes to refer to. This must be a subset of what actual Resource returns
Properties:
# ...
```
Check the `SOMOD::Ref` keyword to know how to refer to the output values.
- **SOMOD::Access**
`SOMOD::Access` controls the accessibility of SOMOD resources. It has three levels of access.
```yaml
Resources:
MyResource1:
Type: ValidResourceType
# SOMOD::Access must be used only as a property of a Resource
SOMOD::Access: module
Properties:
# ...
```
1. `module` - Only the resources in the same module are allowed to refer to this Resource.
2. `scope` - With this access, the Resource can be referenced by any modules in the same scope. The scope groups of similar modules under a single scope name. Read more about the [scope](https://docs.npmjs.com/cli/v8/using-npm/scope) in NPM documentation.
3. `public` - Can be referenced from any module
If not specified, the `scope` is the default value.
`SOMOD::Access` applies to references created using the following SOMOD keywords only. `SOMOD::DependsOn`, `SOMOD::Extend`, `SOMOD::Ref`, `SOMOD::Function`.
- **SOMOD::CreateIf**
Create the resource in the prepared template.yaml only if the provided condition is truthy
```yaml
Resources:
MyResource1:
Type: ValidResourceType
# SOMOD::CreateIf must be used only as a property of a Resource
SOMOD::CreateIf:
# any SOMOD common keywords
Properties:
# ...
```
- **SOMOD::Ref**
Replaces `Ref` and `Fn::GetAtt` to refer to other resources. `SOMOD::Ref` can refer to resources in the same or other dependency modules.
```yaml
Resources:
MyResource1:
Type: ValidResourceType
Properties:
Prop1:
# SOMOD::Ref can be used in the places where the value has to be read from the output of another resource
SOMOD::Ref:
module: my-module
resource: MyResource2
attribute: Name
# ...
```
In the prepared template, SOMOD generates `Fn::GetAtt` when the _attribute_ is referred to, otherwise generates `Ref`.
> Use AWS CloudFormation's `Ref` to refer to [Pseudo Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html)
- **SOMOD::ResourceName**
Use it to generate a unique resource name.
```yaml
Resources:
MyResource1:
Type: ValidResourceType
Properties:
Name:
# SOMOD::ResourceName can be used to define the name of the resource being created, example DynamoDb Table name, Lambda Function Name, ...etc
SOMOD::ResourceName: MyResource
# ...
```
> When deployed, the physical resource names must be unique withh in an AWS Account.
>
> SOMOD Generates resource name in SAM template using the following formula
>
> ```
> SAMResourceName = "somod"+ CloudFormationStackId + (1st 8 characters in the sha256 hash of the module name) + SOMODResourceName
> ```
SOMOD prepare command replaces the SOMOD::Parameter object with the parameter value from parameters.json.
- **SOMOD::Function**
For a Resource of type **`AWS::Serverless::Function`**, `CodeUri` Property must be an object containing `SOMOD::Function` property.
```yaml
Resources:
MyResource1:
Type: AWS::Serverless::Function
Properties:
CodeUri:
# SOMOD::Function must be used only as a value of CodeUri property of AWS::Serverless::Function
SOMOD::Function:
type: CfnCustomResource # type defines the type of the event received by the function handler, type is mandatory
name: getUser # must have a typescript file with this name under serverless/functions directory
customResources: # If this function provides Custom resources, define the JSONSchema for each Custom Resource Type provided by this function
MyCustomResource:
# valid schema for a Custom resource Properties
middlewares: # list of middlewares
- module: my-module-containing-middleware
resource: resource-id-of-the-middleware
# ...
```
- The `type` identifies the type of event this function can handle. must be provided.
- The `name` must be the filename under the `serverless/functions` directory (excluding the extension `.ts`).
- If a function defines the code for [Custom Cloudformation Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html), the developer can specify the schema of the custom resource using the `customResources` property. The customResources is a map of Custom Resource Name to Schema. This property is _Optional_.
- The `middlewares` is the list of middlewares applied to this function. Visit the [Middlewares](/reference/main-concepts/serverless/middlewares) chapter to know more about middlewares in SOMOD.
SOMOD prepare command bundles the function at `.somod/serverless/function/{moduleName}/{functionName}` path
In the prepared template, SOMOD replaces this keyword with the directory path of the bundled function
- **SOMOD::FunctionLayer**
For a Resource of type **`AWS::Serverless::LayerVersion`**, `ContentUri` Property must be an object containing `SOMOD::FunctionLayer` property.
```yaml
Resources:
MyResource1:
Type: AWS::Serverless::LayerVersion
Properties:
ContentUri:
# SOMOD::FunctionLayer must be used only as a value of ContentUri property of AWS::Serverless::LayerVersion
SOMOD::FunctionLayer:
name: getUser
libraries: # list of npm libraries to pack inside the layer.
- my-lib1
content: # Map of file path to file content
"/path/to/my/content1": "MyFileContent1",
"/path/to/my/content1":
# Any valid Common SOMOD keywords to get the content
allowedTypes: # when provided, this layer can only be attached to functions of allowed type
- functionType1
- functionType2
# ...
```
- layer `name` must be provided
- `libraries` must have a list of npm library names as a value. The prepare command generates the content of the layer at `.somod/serverless/functionLayers/{moduleName}/{layerName}`. All of the libraries must be in the `devDependecies` of the current module to help the SOMOD to pick up the specific version during build.
- files from the `content` are created under the layer directory `.somod/serverless/functionLayers/{moduleName}/{layerName}`
Either of the `libraries` or `content` must be provided
- `allowedTypes` help to restrict the type of function to which this layer can be attached. If omitted, the layer is allowed for all types of functions
In the prepared template, SOMOD replaces this keyword with the directory path of the bundled function layer.
- **SOMOD::FunctionMiddleware**
For a Resource of type **`SOMOD::Serverless::FunctionMiddleware`**, `CodeUri` Property must be an object containing `SOMOD::FunctionMiddleware` property.
```yaml
Resources:
MyResource1:
Type: SOMOD::Serverless::FunctionMiddleware
Properties:
CodeUri:
# SOMOD::FunctionMiddleware must be used only as a value of CodeUri property of SOMOD::Serverless::FunctionMiddleware
SOMOD::FunctionMiddleware:
name: logger # must have a typescript file named logger.ts at serverless/functions/middlewares directory
allowedTypes: # when provided, this middleware can only be attached to functions of allowed type
- functionType1
- functionType2
# ...
```
> **Middlewares** allow to insert code to the lambda functions during prepare phase.
> Know more about middlewares in its dedicated [chapter](/reference/main-concepts/serverless/middlewares)
### Outputs
Outputs section in the `serverless/template.yaml` file helps to export the values from deployed stack into parameters. The Outputs section is a map of parameter names to the expression which generates a value from the deployed stack.
Example:
```yaml
Outputs:
my.table.name: # output is exported to this parameter
SOMOD::Ref: # a SOMOD keyword
resource: MyTable1
```
here the default return value from the `MyTable1` resource is exported to `my.table.name` parameter.
After deployment, use the command `npx somod parameters update` to update the values from stack to `parameters.json`
> Read more about parameters [here](/reference/main-concepts/parameters)
> Find more details about the SOMOD CLI [here](/reference/cli)
Now we have understood how to author resources in the template. In the next chapter, Let us understand how to work with Lambda [Functions](/reference/main-concepts/serverless/functions).