Global function to get stack outputs from a cloudformation stack. Useful in tests. Caches so subsequent calls are fast.
Usage:
STACK_NAME=my-app STACK_REGION=eu-west-2 ts-node test.ts
import { CloudFormationClient, DescribeStacksCommand } from '@aws-sdk/client-cloudformation' | |
let cachedOutputs: any | undefined | |
export const getStackOutputs = async () => { | |
if (cachedOutputs) { | |
return cachedOutputs | |
} | |
const cfnClient = new CloudFormationClient({ | |
region: process.env.STACK_REGION, | |
}) | |
const { Stacks } = await cfnClient.send( | |
new DescribeStacksCommand({ | |
StackName: process.env.STACK_NAME, | |
}), | |
) | |
if (!Stacks || !Stacks[0]) { | |
throw new Error('stack not found') | |
} | |
const [{ Outputs }] = Stacks | |
if (!Outputs) { | |
throw new Error('no stack outputs found') | |
} | |
const outputs: Record<string, string> = {} | |
Outputs.forEach((output) => { | |
if (output.OutputKey && output.OutputValue) { | |
outputs[output.OutputKey] = output.OutputValue | |
} | |
}) | |
cachedOutputs = outputs | |
return outputs | |
} |
import { getStackOutputs } from './get-stack-outputs.ts' | |
getStackOutputs() | |
.then(console.log) | |
.catch(console.error) |