Create configmap with outside yaml files for kubernetes

6/29/2021

I'm quite new for kubernetes. I am trying to create configmap with using yaml file which was user defined.

helm upgrade --install test --namespace test --create-namespace . -f xxx/user-defined.yaml

user can add any yaml file with using 'f' option. for example;

cars.yaml
cars:
  - name: Mercedes
    model: E350

So command will be;

helm upgrade --install test --namespace test --create-namespace . -f xxx/cars.yaml

My question is, I want to create configmap which is name 'mercedes-configmap' I need to read that values from cars.yaml and create automaticaly configmap with name and data of cars.yaml

Update, I've created below configmap template;

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Values.cars.name }}-configmap
data:
  {{- range .Files }}
    {{ .Files.Get . | toYaml | quote }}
  {{- end }}

The only issue that I faced, I couldnt get the whole file data.

-- ealpkar
kubernetes
kubernetes-helm

1 Answer

7/2/2021

Welcome to the community!

I have created a helm template for configmap. It works this way: you can pass configmap name - name and file name - fname where data is stored and/or it can read files from a specific folder.

Please find the template (first 3 lines are commented, it's two working implementations of logic to check values existing):

{{/*
{{ if not (or (empty .Values.name) (empty .Values.fname)) }}
*/}}

{{ if and (not (empty .Values.name)) (not (empty .Values.fname)) }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Values.name }}-configmap
data:
  {{- ( .Files.Glob .Values.fname ).AsConfig | nindent 2 }}
---
{{ end }}
{{ $currentScope := .}}
{{ range $path, $_ :=  .Files.Glob  "userfiles/*.yaml" }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ base $path | trimSuffix ".yaml" }}-configmap
data:
  {{- with $currentScope}}
  {{ base $path }}: |
    {{- ( .Files.Get $path ) | nindent 4 }}
  {{- end }}
---
{{ end }}

First part of the template checks if configmap name and file name are set and if so, it renders it. Second part goes to userfiles directory and gets all yamls within.

You find github repo where I shared file examples and configmap.

To render the template with cars2.yaml and with/without files within userfiles directory:

helm template . --set name=cars2 --set fname=cars2.yaml

To render the same template with only files in userfiles directory:

helm template . 

P.S. helm v3.5.4 was used


Useful links:

-- moonkotte
Source: StackOverflow