dagger-helm/dagger.go

83 lines
2.1 KiB
Go
Raw Normal View History

2023-04-06 22:30:09 +02:00
package daggerhelm
import (
"context"
2023-04-07 00:06:38 +02:00
"errors"
2023-04-06 22:30:09 +02:00
"fmt"
2023-04-07 00:06:38 +02:00
"log"
2023-04-06 22:30:09 +02:00
"os"
"path"
"text/template"
"dagger.io/dagger"
)
const CONTAINER_IMAGE = "docker.io/alpine/k8s:1.26.3"
2023-04-07 00:06:38 +02:00
func Compile(
ctx context.Context,
client *dagger.Client,
chartPath string,
valuesFilePath string,
) (*dagger.Directory, error) {
2023-04-06 22:30:09 +02:00
chart := client.Host().Directory(chartPath)
tmpdir := os.TempDir()
2023-04-07 00:06:38 +02:00
tmpdir = path.Join(tmpdir, "helm-dagger")
2023-04-06 22:30:09 +02:00
err := os.MkdirAll(tmpdir, 0755)
if err != nil {
return nil, fmt.Errorf("failed to create tmpdir: %v", err)
}
tmpvalues, err := os.CreateTemp(tmpdir, "")
if err != nil {
return nil, fmt.Errorf("could not create a tempdir. err: %v", err)
}
2023-04-07 00:06:38 +02:00
if _, err := os.Stat(valuesFilePath); errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("the values file does not exist: %v", err)
}
contents, err := os.ReadFile(valuesFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read values file: %v", err)
}
tmpl, err := template.New(valuesFilePath).Delims("[[", "]]").Parse(string(contents))
2023-04-06 22:30:09 +02:00
if err != nil {
return nil, fmt.Errorf("failed to build template for values.yaml, err: %v", err)
}
err = tmpl.Execute(tmpvalues, struct{}{})
if err != nil {
return nil, fmt.Errorf("failed to execute template. err: %v", err)
}
err = tmpvalues.Sync()
if err != nil {
return nil, fmt.Errorf("failed to write to tmpfile. err: %v", err)
}
files, err := os.ReadDir(tmpdir)
if err != nil {
return nil, fmt.Errorf("failed to read tmpdir. err: %v", err)
}
2023-04-07 00:06:38 +02:00
valuesFileDirPath := tmpdir
2023-04-06 22:30:09 +02:00
valuesFileRelativePath := files[0].Name()
2023-04-07 00:06:38 +02:00
log.Println(valuesFileRelativePath)
2023-04-06 22:30:09 +02:00
valuesFile := client.Host().Directory(valuesFileDirPath).File(valuesFileRelativePath)
2023-04-07 00:06:38 +02:00
helmoutput := client.Container().
From(CONTAINER_IMAGE).
WithWorkdir("/mnt").
WithDirectory("chart", chart).
WithFile("chart/values.yaml", valuesFile).
WithWorkdir("/mnt/chart").
WithExec([]string{"helm", "template", ".", "--output-dir", "/mnt/output"})
2023-04-06 22:30:09 +02:00
if exitCode, err := helmoutput.ExitCode(ctx); err != nil || exitCode != 0 {
return nil, fmt.Errorf("failed to render helm chart: %v", err)
}
2023-04-07 00:06:38 +02:00
return helmoutput.Directory("/mnt/output"), nil
2023-04-06 22:30:09 +02:00
}