> For the complete documentation index, see [llms.txt](https://anon-coders-notes.gitbook.io/techwriterdev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anon-coders-notes.gitbook.io/techwriterdev/cloud/aws/developerassociate/services/22_sam/00_basics.md).

# 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**.
* `samconfig.toml` defines the configuration file for SAM application. Should be at root of the location.
* `template.yaml` file which consists of sam template to be deployed at the root of the application.

### SAM Recipe

* Transform Header at the top 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 deploy --guided` will enable us to do interactive deployment.
* `sam build` transforms sam template to cloud formation template.
  * Once build completes, artifacts are generated which will be present in folder `aws-sam`.
* [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.
