2 回答
TA贡献1801条经验 获得超8个赞
我不熟悉 Golang AWS SDK,但如果是我,我在 SDK 文档中找不到它,我会查找 AWS CLI 文档并在那里找到命令,因为它们可能会转换为 SDK 或最坏情况下的运行系统Golang 中的命令来执行 CLI 并获得相同的结果。
GetResources
https://docs.aws.amazon.com/cli/latest/reference/resourcegroupstaggingapi/get-resources.html
返回与位于 AWS 账户的指定区域中的指定标签(键和值)关联的所有标记资源。
因此,您可以使用它来获取具有特定标签的所有资源,然后在 Golang 中迭代结果以仅选择 ELB
看起来您可以在一个命令中按标签和资源进行过滤:
看起来 golang sdk 确实存在该命令
我认为我上面强调的选项可供您使用。
在 Golang 中执行
您将使用诸如 exec 之类的东西。 https://golang.org/pkg/os/exec/
本教程可能包含如何从 exec https://nathanleclaire.com/blog/2014/12/29/shelled-out-commands-in-golang/获取结果
示例代码
package main
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi"
)
const (
// ProviderName is the cloud provider providing loadbalancing functionality
ProviderName = "aws"
)
// ELB is the struct implementing the lbprovider interface
type ELB struct {
client *elb.ELB
elbResourceName string
resourceapiClient *resourcegroupstaggingapi.ResourceGroupsTaggingAPI
}
// NewELB is the factory method for ELB
func NewELB(id string, secret string, region string) (*ELB, error) {
awsConfig := &aws.Config{
Region: aws.String(region),
Credentials: credentials.NewStaticCredentials(id, secret, ""),
}
awsConfig = awsConfig.WithCredentialsChainVerboseErrors(true)
sess, err := session.NewSession(awsConfig)
if err != nil {
return nil, fmt.Errorf("Unable to initialize AWS session: %v", err)
}
return &ELB{
client: elb.New(sess),
resourceapiClient: resourcegroupstaggingapi.New(sess),
elbResourceName: "elasticloadbalancing",
}, nil
}
// GetLoadbalancersByTag gets the loadbalancers by tag
func (e *ELB) GetLoadbalancersByTag(tagKey string, tagValue string) ([]string, error) {
tagFilters := &resourcegroupstaggingapi.TagFilter{}
tagFilters.Key = aws.String(tagKey)
tagFilters.Values = append(tagFilters.Values, aws.String(tagValue))
getResourcesInput := &resourcegroupstaggingapi.GetResourcesInput{}
getResourcesInput.TagFilters = append(getResourcesInput.TagFilters, tagFilters)
getResourcesInput.ResourceTypeFilters = append(
getResourcesInput.ResourceTypeFilters,
aws.String(e.elbResourceName),
)
resources, err := e.resourceapiClient.GetResources(getResourcesInput)
if err != nil {
return nil, err
}
elbs := []string{}
for _, resource := range resources.ResourceTagMappingList {
elbs = append(elbs, strings.Split(*resource.ResourceARN, "/")[1])
}
return elbs, nil
}
TA贡献1811条经验 获得超4个赞
您可以简单地遍历 ELB 列表并按标签过滤。
svc := elbv2.New(...)
input := &elbv2.DescribeLoadBalancersInput{
LoadBalancerArns: []*string{},
}
result, _ := svc.DescribeLoadBalancers(input)
var list_of_arns []*string
for _, lb := range result.LoadBalancers{
list_of_arns = append(list_of_arns, lb.LoadBalancerArn)
}
input2 := &elbv2.DescribeTagsInput{
ResourceArns: list_of_arns,
}
result2, _ := svc.DescribeTags(input2)
fmt.Println(result2.TagDescriptions)
- 2 回答
- 0 关注
- 119 浏览
添加回答
举报