Skip to content
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

Add support for setting kube version on data.helm_template. #985

Merged
merged 4 commits into from
Dec 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 13 additions & 0 deletions helm/data_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,11 @@ func dataTemplate() *schema.Resource {
Computed: true,
Description: "Rendered notes if the chart contains a `NOTES.txt`.",
},
"kube_version": {
Type: schema.TypeString,
Optional: true,
Description: "Kubernetes version used for Capabilities.KubeVersion",
},
},
}
}
Expand Down Expand Up @@ -449,6 +454,14 @@ func dataTemplateRead(ctx context.Context, d *schema.ResourceData, meta interfac
client.Description = d.Get("description").(string)
client.CreateNamespace = d.Get("create_namespace").(bool)

if ver := d.Get("kube_version").(string); ver != "" {
parsedVer, err := chartutil.ParseKubeVersion(ver)
if err != nil {
return diag.FromErr(fmt.Errorf("couldn't parse string %q into kube-version", ver))
}
client.KubeVersion = parsedVer
}

// The following source has been adapted from the source of the helm template command
// https://github.com/helm/helm/blob/v3.5.3/cmd/helm/template.go#L67
client.DryRun = true
Expand Down
79 changes: 79 additions & 0 deletions helm/data_template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package helm

import (
"fmt"
"regexp"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
Expand Down Expand Up @@ -82,6 +83,57 @@ data:
})
}

func TestAccDataTemplate_kubeVersion(t *testing.T) {
name := randName("kube-version")
namespace := randName(testNamespacePrefix)

datasourceAddress := fmt.Sprintf("data.helm_template.%s", testResourceName)

// No kube version set, will fail as v1.20.0.
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{{
Config: testAccDataHelmTemplateKubeVersionNoVersionSet(testResourceName, namespace, name, "1.2.3"),
ExpectError: regexp.MustCompile("chart requires kubeVersion.*"),
}},
})

// Kube Version set but for a to low version.
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{{
Config: testAccDataHelmTemplateKubeVersion(testResourceName, namespace, name, "1.2.3", "1.18.0"),
ExpectError: regexp.MustCompile("chart requires kubeVersion.*"),
}},
})

// Kube Version set but not parsable.
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{{
Config: testAccDataHelmTemplateKubeVersion(testResourceName, namespace, name, "1.2.3", "abcdef"),
ExpectError: regexp.MustCompile(`couldn't parse string "abcdef" into kube-version`),
}},
})

// Kube Version set and above the min version.
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{{
Config: testAccDataHelmTemplateKubeVersion(testResourceName, namespace, name, "1.2.3", "1.22.0"),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(datasourceAddress, "manifests.%", "1"),
resource.TestCheckResourceAttrSet(datasourceAddress, "manifests.templates/deployment.yaml"),
resource.TestCheckResourceAttrSet(datasourceAddress, "manifest"),
),
}},
})
}

func testAccDataHelmTemplateConfigBasic(resource, ns, name, version string) string {
return fmt.Sprintf(`
data "helm_template" "%s" {
Expand Down Expand Up @@ -133,3 +185,30 @@ func testAccDataHelmTemplateConfigTemplates(resource, ns, name, version string)
}
`, resource, name, ns, testRepositoryURL, version)
}

func testAccDataHelmTemplateKubeVersion(resource, ns, name, version, kubeVersion string) string {
return fmt.Sprintf(`
data "helm_template" "%s" {
name = %q
namespace = %q
description = "Test"
repository = %q
chart = "kube-version"
version = %q
kube_version = %q
}
`, resource, name, ns, testRepositoryURL, version, kubeVersion)
}

func testAccDataHelmTemplateKubeVersionNoVersionSet(resource, ns, name, version string) string {
return fmt.Sprintf(`
data "helm_template" "%s" {
name = %q
namespace = %q
description = "Test"
repository = %q
chart = "kube-version"
version = %q
}
`, resource, name, ns, testRepositoryURL, version)
}
7 changes: 7 additions & 0 deletions helm/testdata/charts/kube-version/Chart.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
apiVersion: v2
name: kube-version
description: A chart requiring kube version 1.22 or above
type: application
version: 1.2.3
appVersion: 1.2.3
kubeVersion: ">=1.22.0-0"
42 changes: 42 additions & 0 deletions helm/testdata/charts/kube-version/templates/_helpers.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "kube-version.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "kube-version.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "kube-version.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Common labels
*/}}
{{- define "kube-version.labels" -}}
helm.sh/chart: {{ include "kube-version.chart" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
53 changes: 53 additions & 0 deletions helm/testdata/charts/kube-version/templates/deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "kube-version.fullname" . }}
labels:
{{- include "kube-version.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: {{ .Chart.Name }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- name: http
containerPort: 80
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
49 changes: 49 additions & 0 deletions helm/testdata/charts/kube-version/values.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Default values for kube-version.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

replicaCount: 1

image:
repository: nginx
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: ""

imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""

podAnnotations: {}

podSecurityContext:
{}
# fsGroup: 2000

securityContext:
{}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000

resources:
{}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi

nodeSelector: {}

tolerations: []

affinity: {}
1 change: 1 addition & 0 deletions website/docs/d/template.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ The following attributes are specific to the `helm_template` data source and not
* `is_upgrade` - (Optional) Set .Release.IsUpgrade instead of .Release.IsInstall. Defaults to `false`.
* `show_only` - (Optional) Explicit list of chart templates to render, as Helm does with the `-s` or `--show-only` option. Paths to chart templates are relative to the root folder of the chart, e.g. `templates/deployment.yaml`. If not provided, all templates of the chart are rendered.
* `validate` - (Optional) Validate your manifests against the Kubernetes cluster you are currently pointing at. This is the same validation performed on an install. Defaults to `false`.
* `kube_version` - (Optional) Allows specifying a custom kubernetes version to use when templating.

## Attributes Reference

Expand Down