Skip to content

Instantly share code, notes, and snippets.

@alok87
Created August 25, 2018 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alok87/c09243f0d61772bb1a7b93ce9a295362 to your computer and use it in GitHub Desktop.
Save alok87/c09243f0d61772bb1a7b93ce9a295362 to your computer and use it in GitHub Desktop.
getloadBalancerByTag.go
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment