diff --git a/src/index.ts b/src/index.ts index b48ce11..1039eae 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ export * from './cfnResponse.js' export * from './stackOutput.js' export * from './toObject.js' +export * from './listStackResources.js' diff --git a/src/listStackResources.ts b/src/listStackResources.ts new file mode 100644 index 0000000..a8b90eb --- /dev/null +++ b/src/listStackResources.ts @@ -0,0 +1,48 @@ +import { + ListStackResourcesCommand, + type CloudFormationClient, +} from '@aws-sdk/client-cloudformation' + +/** + * Returns the resources of a stack that match the given resource type. + */ +export const listStackResources = async ( + cf: CloudFormationClient, + stackName: string, + ResourceType: string | Array, // e.g. 'AWS::Lambda::Function' + resources: Array<{ + PhysicalResourceId: string + LogicalResourceId: string + }> = [], + nextToken?: string, +): Promise< + Array<{ + PhysicalResourceId: string + LogicalResourceId: string + }> +> => { + const { StackResourceSummaries, NextToken } = await cf.send( + new ListStackResourcesCommand({ + StackName: stackName, + NextToken: nextToken, + }), + ) + + resources.push( + ...(StackResourceSummaries ?? []) + .filter((res) => + Array.isArray(ResourceType) + ? ResourceType.includes(res.ResourceType ?? '') + : res.ResourceType === ResourceType, + ) + .map(({ LogicalResourceId, PhysicalResourceId }) => ({ + PhysicalResourceId: PhysicalResourceId as string, + LogicalResourceId: LogicalResourceId as string, + })), + ) + + if (NextToken !== undefined) + return listStackResources(cf, stackName, ResourceType, resources, NextToken) + + return resources +}