https://github.com/coderbyheart/typesafe-stack-outputs-cdk
In order to ensure that the outputs of your CloudFormation Stacks are typed properly, you can use this technique.
https://github.com/coderbyheart/typesafe-stack-outputs-cdk
cdk typescript
Last synced: 9 months ago
JSON representation
In order to ensure that the outputs of your CloudFormation Stacks are typed properly, you can use this technique.
- Host: GitHub
- URL: https://github.com/coderbyheart/typesafe-stack-outputs-cdk
- Owner: coderbyheart
- Created: 2022-08-10T22:54:42.000Z (over 3 years ago)
- Default Branch: saga
- Last Pushed: 2022-08-11T09:22:25.000Z (over 3 years ago)
- Last Synced: 2025-02-01T11:11:15.541Z (11 months ago)
- Topics: cdk, typescript
- Language: TypeScript
- Homepage:
- Size: 96.7 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Type-safe stack outputs in AWS CDK
_In order to ensure that the outputs of your CloudFormation Stacks are typed
properly, you can use this technique._
When defining the outputs, use a helper function that is bound to a type that
defines all stack outputs. This ensures that outputs that are created are
defined in the type definition.
```typescript
/**
* This defines the outputs the stack creates
*/
export type StackOutputs = {
bucketName: string;
};
export class MyStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
/**
* A helper function that only allows
* to create outputs that are defined in `StackOutputs`
*/
const output = (name: keyof StackOutputs, value: string) =>
new CfnOutput(this, name, {
value,
});
const bucket = new Bucket(this, "bucket");
output("bucketName", bucket.bucketName);
}
}
```
This enables to use the type that defines the outputs when querying
CloudFormation for the stack outputs.
In the example below we use
[`@nordicsemiconductor/cloudformation-helpers`](https://www.npmjs.com/package/@nordicsemiconductor/cloudformation-helpers),
which simplifies fetching stack outputs and accepts a type for defining which
outputs the stack returns. This will make `outputs` properly typed.
```typescript
const cf = new CloudFormationClient({});
const outputs = await stackOutput(cf)("MyStack");
console.log("Bucket name:", outputs.bucketName);
```
## Run the example
npm ci
npx cdk deploy
# MyStack
# Deployment time: 38.5s
#
# Outputs:
# MyStack.bucketName = mystack-bucket43879c71-1prqx9wocdsp7
npx tsx use-stack-outputs.ts
# Bucket name mystack-bucket43879c71-1prqx9wocdsp7