Skip to content

feat: store coder_workspace_tags in the database #13294

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 27 commits into from
May 20, 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
Next Next commit
WIP
  • Loading branch information
mtojek committed May 17, 2024
commit 8507793a089b8adc4c161ee5b5068644df832110
2 changes: 1 addition & 1 deletion coderd/database/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

115 changes: 110 additions & 5 deletions provisioner/terraform/parse.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package terraform

import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"

"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/mitchellh/go-wordwrap"
"golang.org/x/xerrors"
Expand All @@ -28,6 +33,109 @@ func (s *server) Parse(sess *provisionersdk.Session, _ *proto.ParseRequest, _ <-
return provisionersdk.ParseErrorf("load module: %s", formatDiagnostics(sess.WorkDirectory, diags))
}

workspaceTags, err := s.loadWorkspaceTags(ctx, module)
if err != nil {
return provisionersdk.ParseErrorf("can't load workspace tags: %v", err)
}

templateVariables, err := loadTerraformVariables(module)
if err != nil {
return provisionersdk.ParseErrorf("can't load template variables: %v", err)
}

return &proto.ParseComplete{
TemplateVariables: templateVariables,
WorkspaceTags: workspaceTags,
}
}

var rootTemplateSchema = &hcl.BodySchema{
Blocks: []hcl.BlockHeaderSchema{
{
Type: "data",
LabelNames: []string{"type", "name"},
},
},
}

var coderWorkspaceTagsSchema = &hcl.BodySchema{
Attributes: []hcl.AttributeSchema{
{
Name: "tags",
},
},
}

func (s *server) loadWorkspaceTags(ctx context.Context, module *tfconfig.Module) (map[string]string, error) {
workspaceTags := map[string]string{}

for _, dataResource := range module.DataResources {
if dataResource.Type != "coder_workspace_tags" {
s.logger.Debug(ctx, "skip resource as it is not a coder_workspace_tags", "resource_name", dataResource.Name)
continue
}

var file *hcl.File
var diags hcl.Diagnostics
parser := hclparse.NewParser()
if strings.HasSuffix(dataResource.Pos.Filename, ".tf") {
file, diags = parser.ParseHCLFile(dataResource.Pos.Filename)
} else {
s.logger.Debug(ctx, "only .tf files can be parsed", "filename", dataResource.Pos.Filename)
continue
}

if diags.HasErrors() {
return nil, xerrors.Errorf("can't parse the resource file: %s", diags.Error())
}

// Parse root to find "coder_workspace_tags"
content, _, diags := file.Body.PartialContent(rootTemplateSchema)
if diags.HasErrors() {
return nil, xerrors.Errorf("can't parse the resource file: %s", diags.Error())
}

for _, block := range content.Blocks {
// Parse "coder_workspace_tags" to find all key-value tags
resContent, _, diags := block.Body.PartialContent(coderWorkspaceTagsSchema)
if diags.HasErrors() {
return nil, xerrors.Errorf(`can't parse the resource coder_workspace_tags: %s`, diags.Error())
}

expr := resContent.Attributes["tags"].Expr
tagsExpr, ok := expr.(*hclsyntax.ObjectConsExpr)
if !ok {
return nil, xerrors.Errorf(`"tags" attribute is expected to be a key-value map`)
}

// Parse key-value entries in "coder_workspace_tags"
for _, tagItem := range tagsExpr.Items {
key, err := previewFileContent(tagItem.KeyExpr.Range())
if err != nil {
return nil, xerrors.Errorf("can't preview the resource file: %v", err)
}
value, err := previewFileContent(tagItem.ValueExpr.Range())
if err != nil {
return nil, xerrors.Errorf("can't preview the resource file: %v", err)
}

s.logger.Info(ctx, "workspace tag found", "key", key, "value", value)
workspaceTags[key] = value
}
}
}
return workspaceTags, nil // TODO
}

func previewFileContent(fileRange hcl.Range) (string, error) {
body, err := os.ReadFile(fileRange.Filename)
if err != nil {
return "", err
}

}

func loadTerraformVariables(module *tfconfig.Module) ([]*proto.TemplateVariable, error) {
// Sort variables by (filename, line) to make the ordering consistent
variables := make([]*tfconfig.Variable, 0, len(module.Variables))
for _, v := range module.Variables {
Expand All @@ -38,17 +146,14 @@ func (s *server) Parse(sess *provisionersdk.Session, _ *proto.ParseRequest, _ <-
})

var templateVariables []*proto.TemplateVariable

for _, v := range variables {
mv, err := convertTerraformVariable(v)
if err != nil {
return provisionersdk.ParseErrorf("can't convert the Terraform variable to a managed one: %s", err)
return nil, err
}
templateVariables = append(templateVariables, mv)
}
return &proto.ParseComplete{
TemplateVariables: templateVariables,
}
return templateVariables, nil
}

// Converts a Terraform variable to a template-wide variable, processed by Coder.
Expand Down
54 changes: 53 additions & 1 deletion provisioner/terraform/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func TestParse(t *testing.T) {
// If ErrorContains is not empty, then the ParseComplete should have an Error containing the given string
ErrorContains string
}{
{
/*{
Name: "single-variable",
Files: map[string]string{
"main.tf": `variable "A" {
Expand Down Expand Up @@ -200,6 +200,58 @@ func TestParse(t *testing.T) {
},
},
},
},*/
{
Name: "workspace-tags",
Files: map[string]string{
"parameters.tf": `data "coder_parameter" "os_selector" {
name = "os_selector"
display_name = "Operating System"
mutable = false

default = "osx"

option {
icon = "/icons/linux.png"
name = "Linux"
value = "linux"
}
option {
icon = "/icons/osx.png"
name = "OSX"
value = "osx"
}
option {
icon = "/icons/windows.png"
name = "Windows"
value = "windows"
}
}

data "coder_parameter" "feature_cache_enabled" {
name = "feature_cache_enabled"
display_name = "Enable cache?"
type = "bool"

default = false
}

data "coder_parameter" "feature_debug_enabled" {
name = "feature_debug_enabled"
display_name = "Enable debug?"
type = "bool"

default = true
}`,
"tags.tf": `data "coder_workspace_tags" "custom_workspace_tags" {
tags = {
"cluster" = "developers"
"os" = data.coder_parameter.os_selector.value
"debug" = "${data.coder_parameter.feature_debug_enabled.value}+12345"
"cache" = data.coder_parameter.feature_cache_enabled.value == "true" ? "nix-with-cache" : "no-cache"
}
}`,
},
},
}

Expand Down
Loading