/
tools.go
62 lines (49 loc) · 1.45 KB
/
tools.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package azure
import (
"fmt"
"regexp"
"strings"
"time"
"sylr.dev/libqd/cache"
)
const (
cacheKeyResourceID = `resource-id-%s`
resourceIDPatternText = `(?i)subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/([^/]+)/([^/]+)/(.+)`
)
var (
c = cache.GetCache(1*time.Hour, time.Minute)
resourceIDPattern = regexp.MustCompile(resourceIDPatternText)
)
// ResourceDetails contains details about an Azure resource
type ResourceDetails struct {
SubscriptionID string
ResourceGroup string
Provider string
Type string
Name string
}
// ParseResourceID parses a resource ID into a ResourceDetails struct
// Original code from: https://gist.github.com/vladbarosan/fb2528754cbd97df51ca11fe7be27d2f
func ParseResourceID(resourceID string) (*ResourceDetails, error) {
cacheKey := fmt.Sprintf(cacheKeyResourceID, resourceID)
if cdetails, ok := c.Get(cacheKey); ok {
if details, ok := cdetails.(*ResourceDetails); ok {
return details, nil
}
}
match := resourceIDPattern.FindStringSubmatch(resourceID)
if len(match) == 0 {
return nil, fmt.Errorf("parsing failed for %s. Invalid resource Id format", resourceID)
}
v := strings.Split(match[5], "/")
resourceName := v[len(v)-1]
details := &ResourceDetails{
SubscriptionID: match[1],
ResourceGroup: match[2],
Provider: match[3],
Type: match[4],
Name: resourceName,
}
c.SetDefault(cacheKey, details)
return details, nil
}