Skip to content
This repository has been archived by the owner on Aug 16, 2022. It is now read-only.

fix: Ignore invalid subscriptions #421

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package client
import (
"context"
"errors"
"regexp"

"github.com/Azure/azure-sdk-for-go/services/subscription/mgmt/2020-09-01/subscription"
// Import all autorest modules
Expand All @@ -14,6 +15,10 @@ import (
"github.com/hashicorp/go-hclog"
)

var (
SubscriptionIdRegex = regexp.MustCompile(`^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$`)
)

type Client struct {
subscriptions []string
services map[string]*services.Services
Expand Down Expand Up @@ -98,6 +103,14 @@ func Configure(logger hclog.Logger, config interface{}) (schema.ClientMeta, diag
logger.Info("No subscriptions specified going to using all available ones", "subscriptions", subscriptions)
}

// validate subscriptions
for i, subscriptionId := range client.subscriptions {
if !validateSubscriptionId(subscriptionId) {
logger.Error("Invalid subscription id", "subscription_id", subscriptionId)
client.subscriptions = append(client.subscriptions[:i], client.subscriptions[i+1:]...)
Copy link
Member

@hermanschaaf hermanschaaf Jul 28, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe you can run into trouble if you remove elements from a slice while also ranging over it. Here's a playground demo to illustrate. What you can do, though, is this trick from the SliceTricks page: https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating (that's my good example in the playground)

}
}

if len(client.subscriptions) == 0 {
return nil, diag.FromError(errors.New("could not find any subscription"), diag.USER)
}
Expand All @@ -113,3 +126,7 @@ func Configure(logger hclog.Logger, config interface{}) (schema.ClientMeta, diag
// Return the initialized client and it will be passed to your resources
return client, nil
}

func validateSubscriptionId(subscriptionId string) bool {
return SubscriptionIdRegex.MatchString(subscriptionId)
}