getloadBalancerByTag.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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