You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:31:16