Rusty CDK
This is not an official AWS project.
Rather, it is an attempt to make Infrastructure as Code safer and easier to use by checking as much as possible at compile time.
Think of it as a safe wrapper around unsafe CloudFormation. Also see this blog post.
Usage
Install using cargo:
cargo add rusty-cdk
Now create a stack, and add infrastructure to it by using builders.
use StackBuilder;
use *;
For example, a queue:
use StackBuilder;
use QueueBuilder;
use *;
use ;
See a list of all available builders below.
Once you've done that, you can either synthesize the stack and use any AWS tool (CLI, SDK, console) to deploy it:
let synthesized = stack.synth.unwrap;
Or you can use the built-in deploy function:
deploy.await;
Motivation
This below CDK code is valid at compile time. I.e., it synthesizes (cdk synth) to a CloudFormation template.
// imports
export class CdkStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new Table(this, 'someId', {
tableName: "examples!!!",
partitionKey: {
name: '',
type: AttributeType.BINARY
},
billingMode: BillingMode.PAY_PER_REQUEST,
maxReadRequestUnits: -1,
maxWriteRequestUnits: 0,
})
}
}
But the code will fail at runtime, because it contains various errors:
- table names cannot contain exclamation marks
- the partition key name cannot be empty
- you cannot set
maxReadRequestUnitswhen billing mode isPAY_PER_REQUEST - a
maxReadRequestUnitsof-1does not make sense maxWriteRequestUnitsis similarly not allowed in this situation, and a value of0is a bit special. You're not actually allowed to set this property to zero, but because this is Typescript, the value is interpreted as a falsy and ignored. Meaning the code does not fail, but the resulting stack config is not what you expected.
Fixing these errors can cost a lot of time because you'll only notice them when you're deploying the template.
That leads to a slow feedback loop, where you're constantly fixing issues and going through synth and deploy steps, waiting for AWS to tell you where the next issue might be. In other cases, everything will deploy, but it won't work as expected (see the maxWriteRequestUnits above).
Compare the above with the following:
use *; // importing all wrappers simplifies larger projects
use ;
use ;
use ;
It's about the same amount of code. But partition keys can now only contain alphanumeric characters and underscores, so we create them through a macro that validates this at compile time. And max read capacity cannot be set when you choose provisioned_billing. Also, adding the resources is less magical (you have to pass in the stack builder), but equally safe (you can't build a resource without passing it in).
With this kind of tooling, making mistakes becomes much harder, as some mistakes are caught at compile time and others become impossible.
The library does require you to be somewhat more explicit at times. For example, you have to pick a billing mode, as well as read and write capacity for provisioned billing. The CDK 'helps' you by setting sensible defaults (5 in this particular case). Which can help you get up and running quickly, but is probably not what you want for any real application. Plus, the compile time guarantees should aid you just as much - if not more - in getting stuff deployed.
Approach
This project intends to use the tools that Rust offers for ensuring infrastructure correctness at compile time.
In some cases, Rust offers help out of the box. E.g., it has multiple number types (both signed and unsigned) that aren't falsy.
In addition, macros and type state are the most important additional tools used here.
Const functions would be interesting as well, but they're too limited for the moment (e.g. I can check a const at compile time, but not a let).
But because compile time checks are sometimes impossible or more challenging, there are also some stack level checks that happen at runtime. Which is why building a stack returns a Result that you unwrap at your own risk.
Usage of CloudFormation
Just like the AWS CDK, this project uses CloudFormation to actually create the AWS services you request (unlike Terraform which uses API calls).
The main advantage is that it allows me to build on the strong foundations of CloudFormation, but improving safety and ease of use by creating a facade for the infrastructure. And no need to reinvent the wheel of figuring out the dependency graph, etc.
It also has some disadvantages. One is that CloudFormation is slow, in part because it wants to be able to roll back to a stable version if something does go wrong. That's less important if we're able to make creating the infrastructure completely safe at compile time. No rollbacks = less time lost.
In time, the project might switch to using SDK calls, to try and make things faster as well as easier.
IDs are similar to the AWS CDK
In its core idea (create a programmatic interface for CloudFormation), some terminology and usage, this project is similar to the AWS CDK. And so, just like with the CDK, you should be careful with changing the ids you pass to the builders. These ids are used to identify deployed resources. As such, changing an id is a signal that the resource whose id has been 'removed', will be deleted. Meanwhile, a new resource, with the new, changed id will be created.
E.g. if you have a bucket with id myBuck, and you change the id to myBucket, the bucket in your account is deleted and a new empty one is created.
This can cause issues if you've chosen a name for the resource (again, e.g., a bucket), because CloudFormation want to guarantee rollbacks, meaning a resource is only deleted after its replacement has been successfully created. But that creation cannot take place until the previous name has become available again.
Supported services
Currently only a limited number of services are (partly) supported:
- Appsync
- API Gateway
- AppConfig
- CloudFront
- Cloudwatch logs
- DynamoDB
- IAM
- Lambda
- S3
- SNS
- SQS
In other words, you can create serverless applications with this library.
To be added at some point:
- Athena
- Cloudwatch (-logs)
- CodeBuild
- CodePipeline
- DocumentDB
- ECS
- EventBridge
- Kinesis
- RDS
- Step Functions
- and additional functionality from the already supported services
Available builders
Based on rg '^.*?(\w+Builder).*?$' -N -I -r '$1' | sort | uniq | sed -e 's/^/- /'
- ApiGatewayV2Builder
- AppSyncApiBuilder
- ApplicationBuilder
- AssumeRolePolicyDocumentBuilder
- AuthProviderBuilder
- BucketBuilder
- BucketNotificationBuilder
- BucketPolicyBuilder
- CachePolicyBuilder
- ChannelNamespaceBuilder
- ConfigurationProfileBuilder
- CorsConfigurationBuilder
- CorsRuleBuilder
- DefaultCacheBehaviorBuilder
- DeploymentStrategyBuilder
- DistributionBuilder
- EnvironmentBuilder
- EventConfigBuilder
- EventLogConfigBuilder
- FunctionBuilder
- GenerateSecretStringBuilder
- IntelligentTieringConfigurationBuilder
- InventoryTableConfigurationBuilder
- JournalTableConfigurationBuilder
- LifecycleConfigurationBuilder
- LifecycleRuleBuilder
- LifecycleRuleTransitionBuilder
- LogGroupBuilder
- MetadataConfigurationBuilder
- MetadataDestinationBuilder
- NonCurrentVersionTransitionBuilder
- OriginAccessControlBuilder
- OriginBuilder
- ParametersInCacheKeyAndForwardedToOriginBuilder
- PermissionBuilder
- PolicyBuilder
- PolicyDocumentBuilder
- PrincipalBuilder
- PublicAccessBlockConfigurationBuilder
- QueueBuilder
- QueuePolicyBuilder
- RecordExpirationBuilder
- RoleBuilder
- RolePropertiesBuilder
- SecretBuilder
- StackBuilder
- StatementBuilder
- TableBuilder
- TagFilterBuilder
- TopicBuilder
- TopicPolicyBuilder
- ValidatorBuilder
- ViewerCertificateBuilder
FAQ
- "Where can I find examples of how to use this project?"
- Examples can be found in the
examplesdir - The snapshot tests in the
rusty-cdkdir also provide some usage examples
- Examples can be found in the
- "I can't find field X of resource Y. And I would like to use resource Z, which is currently not supported"
- Check whether it's a legacy field (like
maxTTLinDefaultCacheBehavior). If so, I may not have added it, since there's a newer, recommended, alternative. - If it's not a legacy field, I may not have gotten around to adding it yet. I've focussed on the properties that I think are most commonly used/useful. You can always open an issue, or add it yourself.
- The same goes for unsupported resources: open an issue or PR!
- Check whether it's a legacy field (like
- _"How do I add tags to resources?"
- Currently, you can only add tags to the stack, not to individual resources. These tags are then applied when using the
deploymethod. They are not present in the CloudFormation template, because unfortunately, templates do not have a root property for tags. See an example below. - In theory, CloudFormation should propagate the tags to its resources, in practice it will do so in 80–90% of cases.
- Currently, you can only add tags to the stack, not to individual resources. These tags are then applied when using the
- "I create a resource and my deployment failed"
- If you think that failure could have been avoided at compile time (or before synthesizing), please open an issue
- "Wouldn't it be better if synth / another method was async?"
- Maybe? But keeping everything except for
deploysynchronous is easiest for now.
- Maybe? But keeping everything except for
- "Won't this library always be behind on the latest additions/changes to AWS?"
- Sadly, yes. But for a long time that was the case with CloudFormation as well. And sometimes you have to wait for months or a few years before L2-3 constructs arrive in the AWS CDK.
- "Why don't you use more borrowing in the internals of this library?"
- It started out with less borrowing because that's easier, less complex. And when I experimented with introducing borrowing everywhere, the performance gain was barely noticeable.
- "Why not use regex for the macros?"
- I want to avoid any dependency that I don't strictly need, and most validations are actually relatively simple. Still, if the project keeps growing, I might face the choice between using
regex, or accepting a lot of additional complexity and code.
- I want to avoid any dependency that I don't strictly need, and most validations are actually relatively simple. Still, if the project keeps growing, I might face the choice between using
use StackBuilder;
use QueueBuilder;
async
TODO
- Check duplicate ids in intelligent tiering
- And look where we need similar things
- Allow overriding of Lambda log group
- Similarly, allow overriding of other resources like Bucket Policy of website
- Multiple queue/topic policy = only last one is applied
- Merge the policies during build? Too bad that this is not transparent though
- Prefer the user policy id, not our generated one
- Another option is to pass on a ref (but not sure how to implement yet + forgetting to do that would case issues)
- Remove docs pointing out current limitation
- Merge the policies during build? Too bad that this is not transparent though
- UpdateReplacePolicy/DeletionPolicy for
- DynamoDB
- S3
- Other storage structs
- Most refs should have an 'override' for referring to resources outside the stack
- In some cases, a macro could be used that the resource actually exists
- Improve diff
- Show whether resource has changed
- Ability to invoke deploy, diff and synth (?) from command line
- More help with IAM permissions
- Additional checks for structure of iam policies
- For example
resourcesis not required in all cases, but in most contexts it is
- For example
- Additional checks for structure of iam policies
- Try to replace
synwith more something more compile-time lightweight -facet? - Switch to uploading template to s3? helps avoid the 51 kb limit
- Or at least offer that option
- GitHub actions
- Testing for several platforms
- Semver checks