sigs.k8s.io/cluster-api-provider-aws@v1.5.5/cmd/clusterawsadm/resource/list.go (about) 1 /* 2 Copyright 2021 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package resource 18 19 import ( 20 "fmt" 21 22 "github.com/aws/aws-sdk-go/aws" 23 "github.com/aws/aws-sdk-go/aws/arn" 24 "github.com/aws/aws-sdk-go/aws/session" 25 rgapi "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi" 26 27 infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1beta1" 28 ) 29 30 // ListAWSResource fetches all AWS resources created by CAPA. 31 func ListAWSResource(region, clusterName *string) (AWSResourceList, error) { 32 var resourceList AWSResourceList 33 cfg := aws.Config{} 34 if *region != "" { 35 cfg.Region = region 36 } 37 38 sess, err := session.NewSessionWithOptions(session.Options{ 39 SharedConfigState: session.SharedConfigEnable, 40 Config: cfg, 41 }) 42 if err != nil { 43 return resourceList, err 44 } 45 46 resourceClient := rgapi.New(sess) 47 input := &rgapi.GetResourcesInput{ 48 TagFilters: []*rgapi.TagFilter{}, 49 } 50 51 awsResourceTags := infrav1.Build(infrav1.BuildParams{ 52 ClusterName: *clusterName, 53 Lifecycle: infrav1.ResourceLifecycleOwned, 54 }) 55 56 for tagKey, tagValue := range awsResourceTags { 57 tagFilter := &rgapi.TagFilter{} 58 tagFilter.SetKey(tagKey) 59 tagFilter.SetValues([]*string{aws.String(tagValue)}) 60 input.TagFilters = append(input.TagFilters, tagFilter) 61 } 62 63 output, err := resourceClient.GetResources(input) 64 if err != nil { 65 return resourceList, err 66 } 67 68 if len(output.ResourceTagMappingList) == 0 { 69 fmt.Println("Could not find any AWS resource created by CAPA") 70 return resourceList, nil 71 } 72 73 resourceList = AWSResourceList{ 74 ClusterName: *clusterName, 75 AWSResources: []AWSResource{}, 76 } 77 78 for _, eachResource := range output.ResourceTagMappingList { 79 resourceARN, err := arn.Parse(*eachResource.ResourceARN) 80 if err != nil { 81 return resourceList, err 82 } 83 eachAWSResource := AWSResource{ 84 Partition: resourceARN.Partition, 85 Service: resourceARN.Service, 86 Region: resourceARN.Region, 87 AccountID: resourceARN.AccountID, 88 Resource: resourceARN.Resource, 89 ARN: *eachResource.ResourceARN, 90 } 91 resourceList.AWSResources = append(resourceList.AWSResources, eachAWSResource) 92 } 93 94 return resourceList, nil 95 }