如何使用AWS Go SDK在Cost Explorer中添加多标签过滤资源
问题
使用AWS Go SDK的GetCostAndUsage函数查询成本数据,已实现通过project标签(值为Project1)过滤资源,代码如下:
input := &costexplorer.GetCostAndUsageInput{ TimePeriod: &costexplorer.DateInterval{ Start: aws.String(startdate.Format("2006-01-02")), End: aws.String(enddate.Format("2006-01-02")), }, Granularity: aws.String("MONTHLY"), Metrics: []*string{aws.String("BlendedCost")}, GroupBy: []*costexplorer.GroupDefinition{ { Type: aws.String("DIMENSION"), Key: aws.String("SERVICE"), }, }, Filter: &costexplorer.Expression{ Tags: &costexplorer.TagValues{ Key: aws.String("project"), Values: []*string{aws.String("Project1")}, MatchOptions: []*string{ aws.String("EQUALS"), }, }, }, }
现在需要添加stage标签过滤,只保留值为dev或prod的资源,但直接在Filter中添加重复的Tags字段时,Go提示“duplicate field name tags on struct literal”错误,求正确实现方式。
解决方案
不能在单个Expression里重复定义Tags字段,要通过And字段组合多个标签过滤条件,每个标签对应一个独立的Expression:
input := &costexplorer.GetCostAndUsageInput{ TimePeriod: &costexplorer.DateInterval{ Start: aws.String(startdate.Format("2006-01-02")), End: aws.String(enddate.Format("2006-01-02")), }, Granularity: aws.String("MONTHLY"), Metrics: []*string{aws.String("BlendedCost")}, GroupBy: []*costexplorer.GroupDefinition{ { Type: aws.String("DIMENSION"), Key: aws.String("SERVICE"), }, }, Filter: &costexplorer.Expression{ And: []*costexplorer.Expression{ // 过滤project=Project1的资源 { Tags: &costexplorer.TagValues{ Key: aws.String("project"), Values: []*string{aws.String("Project1")}, MatchOptions: []*string{ aws.String("EQUALS"), }, }, }, // 过滤stage=dev或prod的资源 { Tags: &costexplorer.TagValues{ Key: aws.String("stage"), Values: []*string{aws.String("dev"), aws.String("prod")}, MatchOptions: []*string{ aws.String("EQUALS"), }, }, }, }, }, }
说明
And字段用于组合多个逻辑与的过滤条件,只有同时满足所有条件的资源才会被选中- 每个标签过滤规则对应一个独立的
Expression,各自设置Tags属性 - 对于
stage标签,通过Values数组传入多个可选值,配合EQUALS匹配选项,就能实现“值为dev或prod”的过滤逻辑
内容的提问来源于stack exchange,提问作者Karagee
相关产品推荐
相关产品推荐

