Primeversary Part 2: State Machine
Last time, I talked about a project where I’m making AWS email me and my (future) wife in the morning if we’ve been married a prime number of days. In this post, I’ll talk about the very simple state machine that accomplishes this.
State machines can be built via a low-code web-ui, and that gives use something that looks like this:
In this control flow we start, then run a step called “InvokeIsPrime.” Then we have a choice that either goes straight to “success” and then “end”, or else goes to “SNS Publish” and then “end.”
Let’s take a look at the JSON representation of this state machine:
{
"Comment": "Email us if it's been a prime number of days since the big day!",
"StartAt": "InvokeIsPrime",
"States": {
"InvokeIsPrime": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "primeChecker"
},
"Next": "Choice"
},
"Choice": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.Payload.isPrime",
"BooleanEquals": true,
"Next": "SNS Publish"
}
],
"Default": "Success"
},
"Success": {
"Type": "Succeed"
},
"SNS Publish": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"Message.$": "States.Format('It has been {} days, a prime number!', $.Payload.days)",
"Subject": "Happy primeversary!",
"TopicArn": "arn:aws:sns:<some region>:<some-account-number>:prime-day"
},
"End": true
}
}
}
I think the JSON is a bit harder to create than the image, but it has two big advantages:
- You can see all sorts of details in it, like exactly what lambda function gets invoked
- You can commit it to source control
To be honest, when I was working on this state machine, because this project is a hobby project
and not a mission-critical workload, I mostly edited the state machine directly in the AWS Console
workflow editor, then used the AWS CLI to record this definition.json
and commit it to source control,
so that I could have revision control on it.
Overall, I’d say it a bit easier to do the high level, flow-charty code in, well, a flow chart, and leave the actual maths to the lambda function. It’s definitely possible to build the whole thing as a single lambda, but it was fun to learn a new tool, and I think this approach was a reasonable one for the project.
Next time, we’ll take a look at how the lambda actually works!
Till then, happy learning!
– Will
Love this post? Hate it? Is someone wrong on the internet? Is it me? Please feel free to @me on mastodon
I used to host comments on the blog, but have recently stopped. Previously posted comments will still appear, but for new ones please use the mastodon link above.
Discussion