# Serverless Application Model (SAM)

## Mascot

![AWS SAM Mascot](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-c890d2c1c0a08af91975b2543d35dc63c5487ab9%2FSAM_Mascot.png?alt=media)

## About

* Transform header indicates it's SAM model.
* **Framework for developing and deploying serverless applications**.
* All the configuration is `YAML` code.
* Generate complex CloudFormation from simple SAM `YAML` file.
* Supports anything from CloudFormation such as `Outputs`, `Mappings`, `Parameters`, `Resources` etc.
* SAM can use `CodeDeploy` to deploy Lambda functions.
* SAM can help you to run Lambda, API Gateway, DynamoDB locally.

### SAM Recipe

*   Transform Header indicates it's SAM template.

    ```yaml
    Transform: 'AWS::Serverless-2016-10-31'
    ```
* Write code using [SAM constructs](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-resources-and-properties.html)
* Once SAM template YAML file is created, use `sam deploy` command _( optionally can use `sam package` command)_.
* [SAM commands](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-command-reference.html) helps to build and deploy sam template.
* Can use `sam sync --watch` command to quickly sync local changes to AWS Lambda using `SAM Accelerate`.

### Deep Dive

1. SAML Template YAML is first build using `sam build` command.
2. After build phase, cloud formation template _(YAML)_ file is generated out of it.
3. Zip and upload S3 the artifacts generated to S3 bucket.
4. Use `sam deploy` command to deploy or execute the changeset.
5. CloudFormation stack is made up of `Lambda`, `API Gateway` and `DynamoDB`.

### SAM Accelerate

* It is a set of features to reduce latency while deploying resources to AWS.
* `sam sync` synchronizes the project declared in SAM templates to AWS.
* It can synchronize code changes to AWS without updating infrastructure _(internally it uses service APIs and bypass CloudFormation)_.

#### `sync` command

| Command                                       | Description                                                                                                                                                  |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `sam sync`                                    | Synchronizes code and infrastructure                                                                                                                         |
| `sam sync --code`                             | Synchronizes code changes without updating infrastructure _(bypass CloudFormation, update in seconds)_                                                       |
| `sam sync --code --resource <resource>`       | Synchronize only a specific resource and their dependencies                                                                                                  |
| `sam sync --code --resource-id <resource-id>` | Synchronize only resource with specific resource id and their dependencies                                                                                   |
| `sam sync --watch`                            | <p>Monitor for file changes and automatically synchronize when changes are detected.<br>If includes configuration changes, it uses <code>sam sync</code></p> |

### SAM policy templates

* It is a list of templates to apply permission to your Lambda functions.
* Policy templates list can be found [here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html).
* From the above policy list following are important.
  * `S3ReadPolicy`
  * `SQSPollerPolicy`
  * `DynamoDBCrudPolicy`

### Local Capability

#### Lambda

**Start Lambda**

* By using SAM framework, you can start AWS Lambda locally.
* This will start a local endpoint that emulates AWS Lambda.
* This can be used to run automated test against local endpoint.
* Command : `sam local start-lambda`.

**Invoke Lambda**

* Local invocation can be done using `sam local invoke` command.
* Local invocation will invoke lambda once and quit after invocation completes.
* Helpful for generating test cases.
* If lambda tries to access some other AWS resource make sure to pass the relevant profile using the `--profile` option.

**Generate Event**

* Generate events for lambda functions using command `sam local generate-event`.

#### API Gateway

* Locally start an API Gateway endpoint using the command `sam local start-api`.
* Starts a local `HTTP` server that hosts all your functions.
* Changes to functions are automatically reloaded.

### Multiple environments

* [TOML](https://toml.io/en/) file can be used to configure environment specific parameters.
* This configuration file can be passed while deploying resources using `SAM` command line.
*   Command can be given as follows,

    ```sh
        sam deploy --config-env <env>
        # Example
        sam deploy --config-env prod
    ```

## Integrations

### SAM and CodeDeploy

* SAM Framework natively uses CodeDeploy to update and LambdaFunctions.
* Traffic Shifting features using Alias is used for update.
  * `AutoPublishAlias` Parameter in `SAM` template file takes care of this.
* Pre and Post traffic hooks feature to validate deployment _(before traffic shift starts and after it ends)_.
* Easy and automated rollbacks using `CloudWatch` Alarms.
* Also has capability to provide Deployment Preference like `Canary`, `Linear`, `AllAtOnce`.
* Alarms can trigger a rollback.
