Skip to content

Instantly share code, notes, and snippets.

@vladbarosan
Last active March 21, 2018 23:53
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 vladbarosan/fb2528754cbd97df51ca11fe7be27d2f to your computer and use it in GitHub Desktop.
Save vladbarosan/fb2528754cbd97df51ca11fe7be27d2f to your computer and use it in GitHub Desktop.
Parse azure resource id in go
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