Forin
Forin

Reputation: 1609

Inject file into Helm template

I have a list of properties defined in values.yaml as follows:

files:
 - "file1"
 - "file2"

Then in my template I want to create config maps out of my values.

I came up with the following template:

{{- range $value := .Values.files }}
---
apiVersion: v1
kind: ConfigMap
metadata: 
    name: {{ $value }}
data:
    {{ $value }}: {{ .Files.Get (printf "%s/%s" "files" $value) | indent 4 }}
{{- end }}

As you can see I want to have configmaps with same name as files. I mixed up several parts of documentation, however my template does not work as expected.

How can I achieve configmap creation through templates?

//EDIT I expect to have the following ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata: 
    name: file1
data:
    file1: <file1 content>
---
apiVersion: v1
kind: ConfigMap
metadata: 
    name: file2
data:
    file2: <file2 content>

Upvotes: 1

Views: 3967

Answers (3)

Jon Bates
Jon Bates

Reputation: 3173

It's now possible to use Files.Glob to render the contents of files into ConfigMaps and Secrets using AsConfig and AsSecret respectively

e.g.

apiVersion: v1
kind: ConfigMap
metadata:
  name: MyConifg
data:
{{ (.Files.Glob "files/*").AsConfig | indent 2 }}

In this simple case, you'll end up with 1 ConfigMap which contains an entry for each file, properly escaped and formatted, but it can easily be adapted with a range block to create multiple ConfigMaps

Upvotes: 0

redInk
redInk

Reputation: 725

Try something as below

{{ $currentScope := .}}
{{- range $value := .Values.files }}
---
apiVersion: v1
kind: ConfigMap
metadata:
    name: {{ $value }}
data:
    {{- with $currentScope}}
        {{ $value }}: {{ .Files.Get (printf "%s/%s" "files" $value) | indent 4 }}
    {{- end }}
{{- end }}

My Chart structure

├── Chart.yaml
├── charts
├── files
│   ├── file1
│   └── file2
├── templates
│   ├── configmap.yaml
│   ├── deployment.yaml
│   ├── secret.yaml
│   └── service.yaml
└── values.yaml

Upvotes: 0

Matt
Matt

Reputation: 8132

Try the following:

{{- $files := .Files }}
{{- range $value := .Values.files }}
---
apiVersion: v1
kind: ConfigMap
metadata: 
  name: {{ $value }}
  data:
    {{ $value }}: |
{{ $files.Get (printf "%s/%s" "files" $value) | indent 6 }}
{{- end }}

You problem seems to be with incorrect indentation. Make sure the line with $files.Get starts with no spaces.

And I also added {{- $files := .Files }} to access .Files, because for some reason range is changeing the . scope.

I have found this example in documentation but it seems to work only if file's content are one-line. So if your files are one line only, then you should check the example.

Also notice the | after {{ $value }}:. You need it because file content is a multiline string. Check this StackQuestion on how to use multiline strings in yaml.

Upvotes: 2

Related Questions