# The same stack, written twice

> I deployed the flat with SAM and then rebuilt it in Pulumi, on purpose, to find out where each one actually earns its keep.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2021-10-23
- Tags: Pulumi, SAM, AWS, Infrastructure as Code, CloudFormation, Python
- URL: https://deyanpeev.com/posts/the-same-stack-written-twice

The home automation stack has been running on SAM since January. Over a few
weekends in the autumn I wrote all of it again as a Pulumi program, with the
same tables, same functions, same rules and same alarms. I wasn't migrating, I
wanted to compare them. Comparing two tools on a toy is worthless, and this was
the first stack I had that was small enough to rewrite and still in real use.

It's twenty-one resources, and the two versions differ in a few specific
places.

# SAM is a macro

`AWS::Serverless::Function` isn't really a resource type. It is an instruction
to a CloudFormation transform, which expands it into a function, a role, a log
group and whatever the event sources imply. When that lines up with what you
want, the payoff is absurd:

```yaml
Events:
  SmartHome:
    Type: AlexaSkill
    Properties:
      SkillId: !Ref AlexaSkillId
```

Four lines. They expand into a `Lambda::Permission` with
`alexa-connectedhome.amazon.com` as the principal and the skill id as the event
source token, and I didn't have to know any of that. Same for the IoT rule that
feeds sensor readings in, and for the policy templates:

```yaml
Policies:
  - DynamoDBCrudPolicy:
      TableName: !Ref DeviceRegistryTable
```

Three lines, against a hand-written policy document with six actions and two
ARNs. Across five functions that's the single largest thing SAM saved me, and
it is not close.

You pay for it when you step off the path. Anything SAM has no template for is
raw CloudFormation in the same file, so the template ends up bilingual, with a
few terse serverless resources sitting next to hundred lines of long-hand
alarms. And you can't see what it generates. The permission that lets Alexa call
my function exists, but nowhere I can read it.

# Pulumi has no magic, which cuts both ways

The Pulumi version of that Alexa trigger is what SAM was hiding:

```python
aws.lambda_.Permission(
    "alexa-invoke",
    action="lambda:InvokeFunction",
    function=skill_function.name,
    principal=ALEXA_PRINCIPAL,
    event_source_token=skill_id,
    opts=pulumi.ResourceOptions(parent=self),
)
```

Longer, but I now know what it does. The policy document goes the other way.
SAM was doing that well and Pulumi makes me write it out in full, fifty lines of
JSON in a Python function that I didn't have before.

Pulumi pulls ahead on everything that is a loop. Four scheduled jobs in SAM are
four near-identical thirty-line blocks, and I made the last three by copying the
first and editing strings. A programming language exists to remove that kind of
work. In Pulumi:

```python
SCHEDULES = {
    "sunset": "cron(0/15 * * * ? *)",
    "sunrise": "cron(0/15 * * * ? *)",
    "nightly": "cron(20 1 * * ? *)",
    "energy-report": "cron(0 8 ? * MON *)",
}

for key, expression in SCHEDULES.items():
    function = scheduled_functions.get(key)
    if function is None:
        continue
    self.schedules[key] = self._schedule(key, expression, function, child)
```

The rule, the target and the permission are one private method called four
times. Adding a fifth job is a line in a dict.

It also wins at reading things. The Step Functions definitions live in JSON
files with the task ARN as a placeholder, and in Pulumi the substitution is just
code:

```python
definition=task_function.arn.apply(
    lambda arn: template.replace(PLACEHOLDER, arn)
)
```

`apply` on an output value is the one new concept Pulumi asks you to learn. Once
you have it, the rest feels like Python and not like YAML wearing a costume.

# Dependency order is a real constraint

Writing it twice showed me something the SAM version had been hiding. My
routines need the task function, and my skill function needs the routine ARNs so
it can start them. CloudFormation resolves that from the `!Ref` graph regardless
of where you put the blocks. A Pulumi program is a script, so the order in the
file is the order, and the first version deadlocked on itself until I moved
things around and left a comment saying why:

```python
# Same resources as template.yaml. The order below matters: the routines need
# the task function, and the skill function needs the routine ARNs to start
# them.
```

Being forced to write that down was worth more to me than the rewrite. It's a
real constraint in the architecture and I hadnt noticed it in eight months of
YAML.

# One stack, one account

SAM stays the deploy path here. It's one file and one CLI, `sam build` does the
packaging, and for a single stack in a single account the transform does more
for me than the loops would.

For anything with more than one environment I would use Pulumi, or Terraform,
which I use more of at work. The reason is the same for both. A stack described
in a programming language can have functions in it, and once you have three
environments a function means one change where a copied block means three.

The Pulumi program stays in the repo under `infra/pulumi`. Every resource name
carries the stage, so both stacks can run side by side. That's how I checked
they described the same thing.
