2023-05-15 09:34:05 +00:00
package mutator
import (
"context"
"fmt"
2023-05-16 16:35:39 +00:00
"github.com/databricks/cli/bundle"
"github.com/databricks/cli/bundle/config/variable"
2023-09-11 08:18:43 +00:00
"github.com/databricks/cli/libs/env"
2023-05-15 09:34:05 +00:00
)
const bundleVarPrefix = "BUNDLE_VAR_"
type setVariables struct { }
func SetVariables ( ) bundle . Mutator {
return & setVariables { }
}
func ( m * setVariables ) Name ( ) string {
return "SetVariables"
}
2023-09-11 08:18:43 +00:00
func setVariable ( ctx context . Context , v * variable . Variable , name string ) error {
2023-05-15 09:34:05 +00:00
// case: variable already has value initialized, so skip
if v . HasValue ( ) {
return nil
}
// case: read and set variable value from process environment
envVarName := bundleVarPrefix + name
2023-09-11 08:18:43 +00:00
if val , ok := env . Lookup ( ctx , envVarName ) ; ok {
2023-05-15 09:34:05 +00:00
err := v . Set ( val )
if err != nil {
return fmt . Errorf ( ` failed to assign value "%s" to variable %s from environment variable %s with error: %w ` , val , name , envVarName , err )
}
return nil
}
// case: Set the variable to its default value
if v . HasDefault ( ) {
err := v . Set ( * v . Default )
if err != nil {
return fmt . Errorf ( ` failed to assign default value from config "%s" to variable %s with error: %w ` , * v . Default , name , err )
}
return nil
}
2024-01-04 21:04:42 +00:00
// case: Defined a variable for named lookup for a resource
// It will be resolved later in ResolveResourceReferences mutator
if v . Lookup != nil {
return nil
}
2023-05-15 09:34:05 +00:00
// We should have had a value to set for the variable at this point.
// TODO: use cmdio to request values for unassigned variables if current
2023-05-16 16:35:39 +00:00
// terminal is a tty. Tracked in https://github.com/databricks/cli/issues/379
2023-05-15 09:34:05 +00:00
return fmt . Errorf ( ` no value assigned to required variable %s. Assignment can be done through the "--var" flag or by setting the %s environment variable ` , name , bundleVarPrefix + name )
}
2023-05-24 12:45:19 +00:00
func ( m * setVariables ) Apply ( ctx context . Context , b * bundle . Bundle ) error {
2023-05-15 09:34:05 +00:00
for name , variable := range b . Config . Variables {
2023-09-11 08:18:43 +00:00
err := setVariable ( ctx , variable , name )
2023-05-15 09:34:05 +00:00
if err != nil {
2023-05-24 12:45:19 +00:00
return err
2023-05-15 09:34:05 +00:00
}
}
2023-05-24 12:45:19 +00:00
return nil
2023-05-15 09:34:05 +00:00
}