答案 0 :(得分:3)
我不熟悉Golang AWS开发工具包,但如果是我自己,并且我在SDK文档中找不到它,那么我将查阅AWS CLI文档并在其中找到命令,因为它们可能会转换为SDK或更糟在Golang中运行case命令以执行CLI并获得相同的结果。
https://docs.aws.amazon.com/cli/latest/reference/resourcegroupstaggingapi/get-resources.html
返回所有与 位于指定区域中的指定标签(键和值) AWS帐户。
因此您可以使用它来获取具有特定标记的所有资源,然后在Golang中遍历结果以仅选择ELB
看起来您可以在一个命令中同时按标记和资源进行过滤:
看起来该命令确实存在于golang sdk
我想我上面强调的选项对您可用。
您将使用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
}
答案 1 :(得分:0)
您可以简单地遍历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)