# The template I wrote and the one AWS ran

> SAM is a preprocessor, so the way to price it is to print what it hands CloudFormation. Mine is three times the file I typed.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2021-07-17
- Tags: AWS, SAM, CloudFormation, DynamoDB, Lambda, Infrastructure as Code
- URL: https://deyanpeev.com/posts/the-template-i-wrote-and-the-one-aws-ran

The flat has been deployed with SAM since January and I've never once looked
at what SAM produces. That's a strange thing to be able to say about your own
infrastructure, so on Saturday I printed it.

```bash
aws cloudformation get-template \
  --stack-name home-automation \
  --template-stage Processed \
  --query TemplateBody
```

`template.yaml` is 231 lines. The processed template (the document
CloudFormation was given, after the transform ran) is 704. The argument for
and against the tool is mostly about where that difference comes from.

# One function, expanded

This is one function as I wrote it, all of it.

```yaml
SensorIngestFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: src/sensors/
    Handler: app.handler
    Policies:
      - DynamoDBCrudPolicy:
          TableName: !Ref DeviceRegistryTable
    Events:
      Readings:
        Type: IoTRule
        Properties:
          Sql: "SELECT * FROM 'home/+/state'"
```

Fifteen lines. In the processed template it's four resources: the function,
an IAM role, the IoT topic rule itself, and a `Lambda::Permission` letting that
rule invoke the function. Most of the expansion is in the role.

`DynamoDBCrudPolicy` is two lines. It arrives as this, give or take the
formatting:

```json
{
  "Action": [
    "dynamodb:GetItem", "dynamodb:DeleteItem", "dynamodb:PutItem",
    "dynamodb:Scan", "dynamodb:Query", "dynamodb:UpdateItem",
    "dynamodb:BatchWriteItem", "dynamodb:BatchGetItem",
    "dynamodb:DescribeTable", "dynamodb:ConditionCheckItem"
  ],
  "Resource": [
    {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}",
        { "tableName": { "Ref": "DeviceRegistryTable" } }
      ]
    },
    {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/index/*",
        { "tableName": { "Ref": "DeviceRegistryTable" } }
      ]
    }
  ],
  "Effect": "Allow"
}
```

Plus the `AWSLambdaBasicExecutionRole` managed policy and an assume-role
document naming `lambda.amazonaws.com`. I didn't type those either.

Five functions, so five roles I didn't write and five trust policies I did not
get wrong. And five policy documents that spell partition and region correctly,
because a transform did it and not me at eleven at night. This is the largest
single thing SAM does for this stack, by a long way.

# The permission that exists nowhere I can read

The Alexa trigger is four lines of `Events:` and it becomes a
`Lambda::Permission` with `alexa-connectedhome.amazon.com` as the principal and
the skill id as the event source token. I didn't know that principal existed.
I still couldn't type it from memory.

SAM's deal is that it will get right the things you don't know, and in exchange
those things don't appear in your repository. For six months the only answer to
"why can Alexa call this function" was in a macro that AWS runs and I do not.

I'm fine with that trade. It did take me six months to notice I had made it
though.

# Where the transform gives you nothing

Roughly two-thirds of `template.yaml` isn't SAM at all.

`AWS::Serverless::SimpleTable` is a hash key and that's it (no sort key, no
secondary index), so the device registry is a long-hand `AWS::DynamoDB::Table`.
There is no serverless alarm, so the four CloudWatch alarms are long-hand too,
about twenty-five lines each, and they are the single largest thing in the
file. Anything without a SAM equivalent is plain CloudFormation sitting in the
same document. So the template is bilingual, a few dense serverless resources
next to a long tail of ordinary ones.

Which makes "with SAM or without it" a choice between 231 lines and something
like 420, because the alarms and the table are the same either way. The saving
is real, and nearly all of it is in IAM and in event wiring.

# The CLI is the other half, and it is the half I would miss

Without the transform I'd still have `aws cloudformation package` and
`deploy`, which is most of what `sam deploy` is. What I wouldn't have is
`sam build`, which reads `CodeUri`, resolves `requirements.txt` into
`.aws-sam/build/<Function>/`, and rewrites the template to to point at the
built artefact. I would be doing that in a shell script, badly, and the shell
script would be what broke.

And I wouldn't have this:

```bash
sam local invoke SkillFunction --event events/discovery.json
```

which runs the handler in the Lambda image with the same handler contract and
tells me in two seconds that my discovery response is malformed. A deploy takes
ninety to give me the same answer.

If someone made me choose one half of SAM to keep, I'd keep the CLI and
hand-write the roles.

# What it costs

Not a lot, as far as I can tell.

The diff you review isn't the diff you deploy. A one-line change to a policy
template is a fifty-line change to the document CloudFormation sees, and code
review sees the one line. Most of the time that's the point. Occasionaly it
is how a permission gets wider than anyone intended without anything in the
pull request looking different.

And stack events name resources you never typed. When a deploy fails on
`SensorIngestFunctionRole`, there is no `SensorIngestFunctionRole` to grep for.
You learn the naming convention (logical id plus `Role`, logical id plus event
name for rules) and after that it's fine. But it is a convention you have to
learn, you can't look it up in your own repository.

# A make target for the processed template

Printing the processed template took ten minutes and I should have done it in
January. It's a make target now, and the output is committed under
`infra/generated/` so the expansion shows up in diffs even though nobody
edits it.

I'm keeping SAM. If you use it too, I'd recommend the same make target.
