Last active
March 21, 2018 23:53
-
-
Save vladbarosan/fb2528754cbd97df51ca11fe7be27d2f to your computer and use it in GitHub Desktop.
Parse azure resource id in 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" | |
"regexp" | |
"strings" | |
) | |
func main() { | |
details, err := ParseResourceID("/subscriptions/subid-3-3-4/resourceGroups/regGroupVladdb/providers/Microsoft.Network/LoadBalancer/vladdbresourcetest") | |
if err != nil { | |
fmt.Print(err.Error()) | |
return | |
} | |
fmt.Printf("Fields are: %+v", details) | |
} | |
// ResourceDetails contains details about an Azure resource | |
type ResourceDetails struct { | |
subscription string | |
resourceGroup string | |
provider string | |
resourceType string | |
resourceName string | |
} | |
// ParseResourceID parses a resource ID into a ResourceDetails struct | |
func ParseResourceID(resourceID string) (ResourceDetails, error) { | |
const resourceIDPatternText = `(?i)subscriptions/(.+)/resourceGroups/(.+)/providers/(.+?)/(.+?)/(.+)` | |
resourceIDPattern := regexp.MustCompile(resourceIDPatternText) | |
match := resourceIDPattern.FindStringSubmatch(resourceID) | |
if len(match) == 0 { | |
return ResourceDetails{}, fmt.Errorf("parsing failed for %s. Invalid resource Id format", resourceID) | |
} | |
v := strings.Split(match[5], "/") | |
resourceName := v[len(v)-1] | |
result := ResourceDetails{ | |
subscription: match[1], | |
resourceGroup: match[2], | |
provider: match[3], | |
resourceType: match[4], | |
resourceName: resourceName, | |
} | |
return result, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment