如何用TypeScript CDK获取AWS CloudFormation的可用栈列表?
使用TypeScript CDK获取CloudFormation栈列表
你可以直接借助AWS SDK for JavaScript v3的CloudFormation客户端实现需求,TypeScript CDK本身依赖AWS SDK,无需额外安装依赖。
1. 导入CloudFormation客户端模块
在CDK代码中引入所需模块:
import { CloudFormationClient, ListStacksCommand } from "@aws-sdk/client-cloudformation";
2. 编写获取栈列表的函数
初始化客户端实例并调用ListStacksCommand接口,可按需过滤栈状态:
const getExistingStacks = async (region: string) => { const client = new CloudFormationClient({ region }); const command = new ListStacksCommand({ // 可选:只获取处于活跃状态的栈 StackStatusFilter: [ "CREATE_COMPLETE", "UPDATE_COMPLETE", "ROLLBACK_COMPLETE" ] }); const response = await client.send(command); return response.StackSummaries || []; };
3. 检查SuperStar栈是否存在
调用上述函数,遍历栈列表判断目标栈是否已存在:
const checkSuperStarStackExists = async (region: string) => { const stacks = await getExistingStacks(region); return stacks.some(stack => stack.StackName === "SuperStar"); }; // 在部署逻辑中使用 const targetRegion = "us-east-1"; checkSuperStarStackExists(targetRegion).then(exists => { if (exists) { throw new Error("当前账户已存在SuperStar栈,每个账户仅允许部署一个"); } // 执行后续部署流程 });
注意事项
- 确保CDK执行环境拥有
cloudformation:ListStacks的调用权限 - 若需跨区域检查,可循环初始化不同区域的客户端实例
ListStacksCommand支持更多过滤参数(如创建时间范围),可根据需求调整
内容的提问来源于stack exchange,提问作者Amir Sayyar
相关产品推荐
相关产品推荐

