Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Prompt user to select or create new resource #4418

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
42 changes: 42 additions & 0 deletions cli/azd/pkg/azapi/resource_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
"github.com/azure/azure-dev/cli/azd/pkg/account"
"github.com/azure/azure-dev/cli/azd/pkg/convert"
)

type Resource struct {
Expand Down Expand Up @@ -80,6 +81,47 @@ func (rs *ResourceService) GetResource(
}, nil
}

func (rs *ResourceService) ListSubscriptionResources(
ctx context.Context,
subscriptionId string,
listOptions *armresources.ClientListOptions,
) ([]*ResourceExtended, error) {
client, err := rs.createResourcesClient(ctx, subscriptionId)
if err != nil {
return nil, err
}

// Filter expression on the underlying REST API are different from --query param in az cli.
// https://learn.microsoft.com/en-us/rest/api/resources/resources/list-by-resource-group#uri-parameters
options := armresources.ClientListOptions{}
if listOptions != nil && *listOptions.Filter != "" {
options.Filter = listOptions.Filter
}

resources := []*ResourceExtended{}
pager := client.NewListPager(&options)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return nil, err
}

for _, resource := range page.ResourceListResult.Value {
resources = append(resources, &ResourceExtended{
Resource: Resource{
Id: *resource.ID,
Name: *resource.Name,
Type: *resource.Type,
Location: *resource.Location,
},
Kind: convert.ToValueWithDefault(resource.Kind, ""),
})
}
}

return resources, nil
}

func (rs *ResourceService) ListResourceGroupResources(
ctx context.Context,
subscriptionId string,
Expand Down
26 changes: 23 additions & 3 deletions cli/azd/pkg/azure/arm_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,36 @@ type AutoGenInput struct {
MinSpecial *uint `json:"minSpecial,omitempty"`
}

// ResourceInputMetadata is set on ARM/Bicep parameter properties
// This metadata is used to generate a resource picker in the CLI
type ResourceInputMetadata struct {
DisplayName string `json:"displayName"`
Description string `json:"description"`
Type string `json:"type"`
Kinds []string `json:"kind"`
}

// OptionalResource is used to represent a resource that may or may not exist in the Azure subscription.
// This value is used as an input value to the ARM/Bicep parameter for parameters with azd type resource metadata.
type OptionalResource struct {
Name string `json:"name"`
SubscriptionId string `json:"subscriptionId"`
ResourceGroup string `json:"resourceGroup"`
Exists bool `json:"exists"`
}

type AzdMetadataType string

const AzdMetadataTypeLocation AzdMetadataType = "location"
const AzdMetadataTypeGenerate AzdMetadataType = "generate"
const AzdMetadataTypeGenerateOrManual AzdMetadataType = "generateOrManual"
const AzdMetadataTypeResource AzdMetadataType = "resource"

type AzdMetadata struct {
Type *AzdMetadataType `json:"type,omitempty"`
AutoGenerateConfig *AutoGenInput `json:"config,omitempty"`
DefaultValueExpr *string `json:"defaultValueExpr,omitempty"`
Type *AzdMetadataType `json:"type,omitempty"`
AutoGenerateConfig *AutoGenInput `json:"config,omitempty"`
DefaultValueExpr *string `json:"defaultValueExpr,omitempty"`
Resource *ResourceInputMetadata `json:"resource,omitempty"`
}

// Description returns the value of the "Description" string metadata for this parameter or empty if it can not be found.
Expand Down
47 changes: 47 additions & 0 deletions cli/azd/pkg/infra/provisioning/bicep/bicep_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1880,6 +1880,53 @@ func (p *BicepProvider) ensureParameters(
continue
}

// Prompt user to specify an existing resource to link to the template
if hasMetadata &&
azdMetadata.Type != nil && *azdMetadata.Type == azure.AzdMetadataTypeResource &&
azdMetadata.Resource != nil {

// Prompt user to select an existing resource to link to the template
selectedResource, err := p.prompters.PromptResource(ctx, prompt.PromptResourceOptions{
ResourceType: azdMetadata.Resource.Type,
Kinds: azdMetadata.Resource.Kinds,
DisplayName: azdMetadata.Resource.DisplayName,
Description: azdMetadata.Resource.Description,
})

if err != nil {
return nil, fmt.Errorf("prompting for resource: %w", err)
}

armResourceValue := azure.OptionalResource{}

// User opted to create a new resource
if selectedResource.Id == "" {
armResourceValue.Exists = false
armResourceValue.Name = selectedResource.Name
armResourceValue.SubscriptionId = p.env.GetSubscriptionId()
armResourceValue.ResourceGroup = p.env.Getenv(environment.ResourceGroupEnvVarName)
} else {
// User selected an existing resource
parsedResource, err := arm.ParseResourceID(selectedResource.Id)
if err != nil {
return nil, fmt.Errorf("parsing resource id: %w", err)
}

armResourceValue.Exists = true
armResourceValue.Name = parsedResource.Name
armResourceValue.SubscriptionId = parsedResource.SubscriptionID
armResourceValue.ResourceGroup = parsedResource.ResourceGroupName
}

configuredParameters[key] = azure.ArmParameterValue{
Value: armResourceValue,
}

mustSetParamAsConfig(key, armResourceValue, p.env.Config, false)
configModified = true
continue
}

// No saved value for this required parameter, we'll need to prompt for it.
parameterPrompts = append(parameterPrompts, struct {
key string
Expand Down
87 changes: 87 additions & 0 deletions cli/azd/pkg/prompt/prompter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import (
"fmt"
"log"
"os"
"path/filepath"
"slices"
"strconv"
"strings"

"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
"github.com/MakeNowJust/heredoc/v2"
"github.com/azure/azure-dev/cli/azd/pkg/account"
"github.com/azure/azure-dev/cli/azd/pkg/azapi"
Expand All @@ -27,6 +30,7 @@ type Prompter interface {
PromptSubscription(ctx context.Context, msg string) (subscriptionId string, err error)
PromptLocation(ctx context.Context, subId string, msg string, filter LocationFilterPredicate) (string, error)
PromptResourceGroup(ctx context.Context) (string, error)
PromptResource(ctx context.Context, options PromptResourceOptions) (*azapi.ResourceExtended, error)
}

type DefaultPrompter struct {
Expand Down Expand Up @@ -160,6 +164,89 @@ func (p *DefaultPrompter) PromptResourceGroup(ctx context.Context) (string, erro
return name, nil
}

type PromptResourceOptions struct {
ResourceType string
Kinds []string
DisplayName string
Description string
}

// PromptResource prompts the user to select a resource with the specified resource type.
// If the user selects to create a new resource, the user will be prompted to enter a name for the new resource.
// This new resource is intended to be created in the Bicep deployment
func (p *DefaultPrompter) PromptResource(
ctx context.Context,
options PromptResourceOptions,
) (*azapi.ResourceExtended, error) {
resourceListOptions := &armresources.ClientListOptions{}
if options.ResourceType != "" {
resourceListOptions.Filter = to.Ptr(fmt.Sprintf("resourceType eq '%s'", options.ResourceType))
}

if options.DisplayName == "" {
options.DisplayName = filepath.Base(options.ResourceType)
}

resourceTypeDisplayName := strings.ToLower(options.DisplayName)

resources, err := p.resourceService.ListSubscriptionResources(ctx, p.env.GetSubscriptionId(), resourceListOptions)
if err != nil {
return nil, fmt.Errorf("listing subscription resources: %w", err)
}

slices.SortFunc(resources, func(a, b *azapi.ResourceExtended) int {
return strings.Compare(a.Name, b.Name)
})

filteredResources := []*azapi.ResourceExtended{}
for _, resource := range resources {
if len(options.Kinds) > 0 && !slices.Contains(options.Kinds, resource.Kind) {
continue
}

filteredResources = append(filteredResources, resource)
}

choices := make([]string, len(filteredResources)+1)
choices[0] = fmt.Sprintf("Create a new %s", resourceTypeDisplayName)

for idx, resource := range filteredResources {
parsedResource, err := arm.ParseResourceID(resource.Id)
if err != nil {
return nil, fmt.Errorf("parsing resource id: %w", err)
}

choices[idx+1] = fmt.Sprintf("%d. %s (Resource Group: %s)", idx+1, resource.Name, parsedResource.ResourceGroupName)
}

selectedIndex, err := p.console.Select(ctx, input.ConsoleOptions{
Message: fmt.Sprintf("Select a %s to use:", resourceTypeDisplayName),
Options: choices,
Help: options.Description,
})
if err != nil {
return nil, fmt.Errorf("selecting %s: %w", resourceTypeDisplayName, err)
}

if selectedIndex > 0 {
return filteredResources[selectedIndex-1], nil
}

name, err := p.console.Prompt(ctx, input.ConsoleOptions{
Message: fmt.Sprintf("Enter a name for the new %s:", resourceTypeDisplayName),
})
if err != nil {
return nil, fmt.Errorf("prompting for %s name: %w", resourceTypeDisplayName, err)
}

return &azapi.ResourceExtended{
Resource: azapi.Resource{
Name: name,
Type: options.ResourceType,
},
}, nil
}

func (p *DefaultPrompter) getSubscriptionOptions(ctx context.Context) ([]string, []string, any, error) {
subscriptionInfos, err := p.accountManager.GetSubscriptions(ctx)
if err != nil {
Expand Down
Loading