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

如何通过AWS SDK v3 CloudFormation客户端获取堆栈标签?

使用AWS JavaScript SDK v3获取CloudFormation堆栈标签

在CloudFormation的JS SDK v3中,同样可以通过ListTagsForResourceCommand来获取堆栈标签,只需分两步操作:先获取所有堆栈的ARN,再逐个查询对应标签。

完整示例代码

ES Modules 导入方式

import { CloudFormationClient, ListStacksCommand, ListTagsForResourceCommand } from "@aws-sdk/client-cloudformation";

// 初始化客户端
const config = { /* 你的AWS配置,比如region等 */ };
const cfClient = new CloudFormationClient(config);

async function getStacksWithTags() {
  // 第一步:获取所有堆栈列表,提取堆栈ARN
  const listStacksInput = {
    StackStatusFilter: ["CREATE_COMPLETE", "UPDATE_COMPLETE"] // 可根据需求筛选堆栈状态
  };
  const listStacksCommand = new ListStacksCommand(listStacksInput);
  const stacksResponse = await cfClient.send(listStacksCommand);

  // 第二步:遍历每个堆栈,获取对应的标签
  const stacksWithTags = await Promise.all(
    stacksResponse.StackSummaries.map(async (stack) => {
      const tagsInput = {
        ResourceArn: stack.StackId // 堆栈的ARN对应StackId字段
      };
      const tagsCommand = new ListTagsForResourceCommand(tagsInput);
      const tagsResponse = await cfClient.send(tagsCommand);

      return {
        StackName: stack.StackName,
        StackId: stack.StackId,
        Tags: tagsResponse.Tags
      };
    })
  );

  return stacksWithTags;
}

// 调用函数并输出结果
getStacksWithTags().then(result => console.log(result)).catch(err => console.error(err));

CommonJS 导入方式

const { CloudFormationClient, ListStacksCommand, ListTagsForResourceCommand } = require("@aws-sdk/client-cloudformation");

// 初始化客户端
const config = { /* 你的AWS配置,比如region等 */ };
const cfClient = new CloudFormationClient(config);

async function getStacksWithTags() {
  // 第一步:获取所有堆栈列表,提取堆栈ARN
  const listStacksInput = {
    StackStatusFilter: ["CREATE_COMPLETE", "UPDATE_COMPLETE"] // 可根据需求筛选堆栈状态
  };
  const listStacksCommand = new ListStacksCommand(listStacksInput);
  const stacksResponse = await cfClient.send(listStacksCommand);

  // 第二步:遍历每个堆栈,获取对应的标签
  const stacksWithTags = await Promise.all(
    stacksResponse.StackSummaries.map(async (stack) => {
      const tagsInput = {
        ResourceArn: stack.StackId // 堆栈的ARN对应StackId字段
      };
      const tagsCommand = new ListTagsForResourceCommand(tagsInput);
      const tagsResponse = await cfClient.send(tagsCommand);

      return {
        StackName: stack.StackName,
        StackId: stack.StackId,
        Tags: tagsResponse.Tags
      };
    })
  );

  return stacksWithTags;
}

// 调用函数并输出结果
getStacksWithTags().then(result => console.log(result)).catch(err => console.error(err));

关键说明

  • CloudFormation的ListTagsForResourceCommand用法逻辑和MGN完全一致,仅需传入堆栈的StackId作为ResourceArn参数。
  • 通过StackStatusFilter可筛选特定状态的堆栈,避免处理未完成或已删除的无效堆栈。

内容的提问来源于stack exchange,提问作者user10223479

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:52:30