2023-05-15 09:34:05 +00:00
package mutator
import (
"context"
2023-05-16 16:35:39 +00:00
"github.com/databricks/cli/bundle"
"github.com/databricks/cli/bundle/config/variable"
2024-03-25 14:18:47 +00:00
"github.com/databricks/cli/libs/diag"
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"
}
2024-03-25 14:18:47 +00:00
func setVariable ( ctx context . Context , v * variable . Variable , name string ) diag . Diagnostics {
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 {
2024-06-26 10:25:32 +00:00
if v . IsComplex ( ) {
return diag . Errorf ( ` setting via environment variables (%s) is not supported for complex variable %s ` , envVarName , name )
}
2023-05-15 09:34:05 +00:00
err := v . Set ( val )
if err != nil {
2024-03-25 14:18:47 +00:00
return diag . Errorf ( ` failed to assign value "%s" to variable %s from environment variable %s with error: %v ` , val , name , envVarName , err )
2023-05-15 09:34:05 +00:00
}
return nil
}
2024-06-19 08:03:06 +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
// case: Set the variable to its default value
if v . HasDefault ( ) {
2024-06-26 10:25:32 +00:00
err := v . Set ( v . Default )
2023-05-15 09:34:05 +00:00
if err != nil {
2024-06-26 10:25:32 +00:00
return diag . Errorf ( ` failed to assign default value from config "%s" to variable %s with error: %v ` , v . Default , name , err )
2023-05-15 09:34:05 +00:00
}
return nil
}
// We should have had a value to set for the variable at this point.
2024-03-25 14:18:47 +00:00
return diag . 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-15 09:34:05 +00:00
}
2024-03-25 14:18:47 +00:00
func ( m * setVariables ) Apply ( ctx context . Context , b * bundle . Bundle ) diag . Diagnostics {
var diags diag . Diagnostics
2023-05-15 09:34:05 +00:00
for name , variable := range b . Config . Variables {
2024-03-25 14:18:47 +00:00
diags = diags . Extend ( setVariable ( ctx , variable , name ) )
if diags . HasError ( ) {
return diags
2023-05-15 09:34:05 +00:00
}
}
2024-03-25 14:18:47 +00:00
return diags
2023-05-15 09:34:05 +00:00
}