Skip to content

feat: evaluate provisioner tags #13333

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

Merged
merged 9 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Works
  • Loading branch information
mtojek committed May 22, 2024
commit 00533fa67de0e7b971735b4293cfb9702dafe02c
58 changes: 55 additions & 3 deletions coderd/wsbuilder/wsbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"time"

"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"

"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/provisionersdk"

Expand Down Expand Up @@ -670,12 +673,61 @@ func (b *Builder) getProvisionerTags() (map[string]string, error) {
tags[name] = value
}

// TODO: Take "workspaceTags", evaluate expressions using parameters, update "tags" map
log.Println(workspaceTags, parameterNames, parameterValues)
evalCtx := buildParametersEvalContext(parameterNames, parameterValues)
for _, workspaceTag := range workspaceTags {
expr, diags := hclsyntax.ParseExpression([]byte(workspaceTag.Value), "partial.hcl", hcl.InitialPos)
if diags.HasErrors() {
return nil, BuildError{http.StatusBadRequest, "failed to parse workspace tag value", xerrors.Errorf(diags.Error())}
}

val, diags := expr.Value(evalCtx)
if diags.HasErrors() {
return nil, BuildError{http.StatusBadRequest, "failed to evaluate workspace tag value", xerrors.Errorf(diags.Error())}
}

// Do not use "val.AsString()" as it can panic
Copy link
Member

Choose a reason for hiding this comment

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

😭

str, err := ctyValueString(val)
if err != nil {
return nil, BuildError{http.StatusBadRequest, "failed to marshal cty.Value as string", err}
}
tags[workspaceTag.Key] = str
}
return tags, nil
}

func buildParametersEvalContext(names, values []string) *hcl.EvalContext {
m := map[string]cty.Value{}
for i, name := range names {
m[name] = cty.MapVal(map[string]cty.Value{
"value": cty.StringVal(values[i]),
})
}
return &hcl.EvalContext{
Variables: map[string]cty.Value{
"data": cty.MapVal(map[string]cty.Value{
"coder_parameter": cty.MapVal(m),
}),
},
}
}

func ctyValueString(val cty.Value) (string, error) {
switch val.Type() {
case cty.Bool:
if val.True() {
return "true", nil
} else {
return "false", nil
}
case cty.Number:
return val.AsBigFloat().String(), nil
case cty.String:
return val.AsString(), nil
default:
return "", xerrors.Errorf("only primitive types are supported - bool, number, and string")
}
}

func (b *Builder) getTemplateVersionWorkspaceTags() ([]database.TemplateVersionWorkspaceTag, error) {
if b.templateVersionWorkspaceTags != nil {
return *b.templateVersionWorkspaceTags, nil
Expand Down
44 changes: 38 additions & 6 deletions coderd/wsbuilder/wsbuilder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func TestBuilder_Reason(t *testing.T) {
withWorkspaceTags(inactiveVersionID, nil),

// Outputs
expectProvisionerJob(func(job database.InsertProvisionerJobParams) {
expectProvisionerJob(func(_ database.InsertProvisionerJobParams) {
}),
withInTx,
expectBuild(func(bld database.InsertWorkspaceBuildParams) {
Expand Down Expand Up @@ -254,20 +254,33 @@ func TestBuilder_ActiveVersion(t *testing.T) {
func TestWorkspaceBuildWithTags(t *testing.T) {
t.Parallel()

asrt := assert.New(t)
req := require.New(t)

workspaceTags := []database.TemplateVersionWorkspaceTag{
{
Key: "fruits_tag",
Value: "data.coder_parameter.number_of_apples.value + data.coder_parameter.number_of_oranges.value",
},
{
Key: "cluster_tag",
Value: "developers",
Value: `"best_developers"`,
},
{
Key: "project_tag",
Value: `"${data.coder_parameter.project.value}+12345"`,
},
{
Key: "team_tag",
Value: `"data.coder_parameter.team.value`,
Value: `data.coder_parameter.team.value`,
},
{
Key: "yes_or_no",
Value: `data.coder_parameter.is_debug_build.value`,
},
{
Key: "actually_no",
Value: `!data.coder_parameter.is_debug_build.value`,
},
{
Key: "is_debug_build",
Expand All @@ -279,13 +292,15 @@ func TestWorkspaceBuildWithTags(t *testing.T) {
// Parameters can be mutable although it is discouraged as the workspace can be moved between provisioner nodes.
{Name: "project", Description: "This is first parameter", Mutable: true, Options: json.RawMessage("[]")},
{Name: "team", Description: "This is second parameter", Mutable: true, DefaultValue: "godzilla", Options: json.RawMessage("[]")},
{Name: "is_debug_build", Type: "bool", Description: "This is third parameter", Mutable: false, Options: json.RawMessage("[]")},
{Name: "is_debug_build", Type: "bool", Description: "This is third parameter", Mutable: false, DefaultValue: "false", Options: json.RawMessage("[]")},
{Name: "number_of_apples", Type: "number", Description: "This is fourth parameter", Mutable: false, DefaultValue: "4", Options: json.RawMessage("[]")},
{Name: "number_of_oranges", Type: "number", Description: "This is fifth parameter", Mutable: false, DefaultValue: "6", Options: json.RawMessage("[]")},
}

buildParameters := []codersdk.WorkspaceBuildParameter{
{Name: "project", Value: "foobar-foobaz"},
// "team" parameter is skipped, so default value is selected
{Name: "is_debug_build", Value: "true"},
// Parameters "team", "number_of_apples", "number_of_oranges" are skipped, so default value is selected
}

ctx, cancel := context.WithCancel(context.Background())
Expand All @@ -301,7 +316,24 @@ func TestWorkspaceBuildWithTags(t *testing.T) {
withWorkspaceTags(inactiveVersionID, workspaceTags),

// Outputs
expectProvisionerJob(func(_ database.InsertProvisionerJobParams) {}),
expectProvisionerJob(func(job database.InsertProvisionerJobParams) {
asrt.Len(job.Tags, 10)

expected := database.StringMap{
"actually_no": "false",
"cluster_tag": "best_developers",
"fruits_tag": "10",
"is_debug_build": "in-debug-mode",
"project_tag": "foobar-foobaz+12345",
"team_tag": "godzilla",
"yes_or_no": "true",

"scope": "user",
"version": "inactive",
"owner": userID.String(),
}
asrt.Equal(job.Tags, expected)
}),
withInTx,
expectBuild(func(_ database.InsertWorkspaceBuildParams) {}),
expectBuildParameters(func(_ database.InsertWorkspaceBuildParametersParams) {
Expand Down
Loading