如何通过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
相关产品推荐
相关产品推荐

