github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/workspace/load_workspace.go (about)

     1  package workspace
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"time"
     8  
     9  	"github.com/spf13/viper"
    10  	"github.com/turbot/steampipe/pkg/constants"
    11  	"github.com/turbot/steampipe/pkg/error_helpers"
    12  	"github.com/turbot/steampipe/pkg/steampipeconfig/inputvars"
    13  	"github.com/turbot/steampipe/pkg/steampipeconfig/modconfig"
    14  	"github.com/turbot/terraform-components/terraform"
    15  )
    16  
    17  func LoadWorkspacePromptingForVariables(ctx context.Context) (*Workspace, error_helpers.ErrorAndWarnings) {
    18  	t := time.Now()
    19  	defer func() {
    20  		log.Printf("[TRACE] Workspace load took %dms\n", time.Since(t).Milliseconds())
    21  	}()
    22  	w, inputVariables, errAndWarnings := LoadWorkspaceVars(ctx)
    23  	if errAndWarnings.GetError() != nil {
    24  		return w, errAndWarnings
    25  	}
    26  
    27  	// load the workspace mod
    28  	errAndWarnings = w.LoadWorkspaceMod(ctx, inputVariables)
    29  	return w, errAndWarnings
    30  }
    31  
    32  func promptForMissingVariables(ctx context.Context, missingVariables []*modconfig.Variable, workspacePath string) error {
    33  	fmt.Println()                                       //nolint:forbidigo // UI formatting
    34  	fmt.Println("Variables defined with no value set.") //nolint:forbidigo // UI formatting
    35  	for _, v := range missingVariables {
    36  		variableName := v.ShortName
    37  		variableDisplayName := fmt.Sprintf("var.%s", v.ShortName)
    38  		// if this variable is NOT part of the workspace mod, add the mod name to the variable name
    39  		if v.Mod.ModPath != workspacePath {
    40  			variableDisplayName = fmt.Sprintf("%s.var.%s", v.ModName, v.ShortName)
    41  			variableName = fmt.Sprintf("%s.%s", v.ModName, v.ShortName)
    42  		}
    43  		r, err := promptForVariable(ctx, variableDisplayName, v.GetDescription())
    44  		if err != nil {
    45  			return err
    46  		}
    47  		addInteractiveVariableToViper(variableName, r)
    48  	}
    49  	return nil
    50  }
    51  
    52  func promptForVariable(ctx context.Context, name, description string) (string, error) {
    53  	uiInput := &inputvars.UIInput{}
    54  	rawValue, err := uiInput.Input(ctx, &terraform.InputOpts{
    55  		Id:          name,
    56  		Query:       name,
    57  		Description: description,
    58  	})
    59  
    60  	return rawValue, err
    61  }
    62  
    63  func addInteractiveVariableToViper(name string, rawValue string) {
    64  	varMap := viper.GetStringMap(constants.ConfigInteractiveVariables)
    65  	varMap[name] = rawValue
    66  	viper.Set(constants.ConfigInteractiveVariables, varMap)
    67  }