Helm
Kubernetes
Namespace
Templates
DevOps

How to create a namespace if it doesn't exists from HELM templates?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When deploying applications on Kubernetes using Helm charts, a common requirement is to ensure that a specific namespace exists before creating resources within it. For those who are new to Helm or need guidance on namespaces, this article provides a detailed explanation of creating a namespace within a Helm template if it does not already exist.

Technical Overview

Kubernetes is a powerful container orchestration system, and namespaces are a way to organize and manage resources within a Kubernetes cluster. Helm is a package manager for Kubernetes, which simplifies the deployment of applications. When deploying applications, ensuring that the target namespace exists beforehand is crucial for successful deployment.

Using Helm Templates to Handle Namespaces

Helm allows for the templating of Kubernetes resources. This flexibility can be used to create namespaces dynamically if they don't exist. Below is a step-by-step guide on how to achieve this.

Step 1: Create a Custom Helper Template

Helm uses Go templates, and you can leverage this powerful templating engine to manage namespaces. A common practice is to create a _helpers.tpl file to manage template blocks that can be reused across different templates in the chart.

Contents of _helpers.tpl:

yaml
1{{- define "create-namespace" -}}
2apiVersion: v1
3kind: Namespace
4metadata:
5  name: {{ .Values.namespace }}
6{{- end -}}

Step 2: Use the Helper Template in Kubernetes Manifests

To use the helper template, reference it in the templates directory. Here is an example using a deployment manifest:

Contents of deployment.yaml:

yaml
1{{- template "create-namespace" . }}
2
3apiVersion: apps/v1
4kind: Deployment
5metadata:
6  name: {{ .Release.Name }}
7  namespace: {{ .Values.namespace }}
8spec:
9  replicas: 1
10  template:
11    metadata:
12      labels:
13        app: {{ .Release.Name }}
14    spec:
15      containers:
16        - name: myapp-container
17          image: busybox
18          command: ['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']

Step 3: Update values.yaml

values.yaml is where Helm stores default values for templates. Ensure it includes a namespace key:

yaml
namespace: "mynamespace"

Step 4: Adding a Conditional Namespace Create Block (Optional)

To ensure the namespace isn't created if it already exists, dependency on Kubernetes' idempotent API behavior or pre-install hooks can be used instead of revisioning and logic in Helm templates. Helm does not natively support conditionally existing resources without the engine expecting a deterministic output, which makes pre-install hooks the preferable choice here when in the chart lifecycle:

Contents of namespace.yaml:

yaml
1apiVersion: v1
2kind: Namespace
3metadata:
4  name: {{ .Values.namespace }}
5
6---
7apiVersion: batch/v1
8kind: Job
9metadata:
10  name: pre-install-job
11  namespace: kube-system
12  annotations:
13    "helm.sh/hook": pre-install
14spec:
15  template:
16    spec:
17      containers:
18        - name: namespace-check
19          image: busybox
20          command: ['sh', '-c', 'kubectl create namespace {{ .Values.namespace }} || echo "Namespace exists."']
21      restartPolicy: OnFailure
22  backoffLimit: 4

Key Points to Remember

Here is a summary table of the key points:

Key PointsDetails
NamespaceLogical partition within a Kubernetes cluster for separating resources.
Helm ChartA collection of files describing a set of Kubernetes resources.
_helpers.tplTemplate file for defining reusable blocks in Helm charts.
Values.yamlThe default configuration for the Helm chart, allows overriding of values.
IdempotencyKubernetes API supports it, allowing safe application of the same manifest multiple times.
Pre-install hooksMechanism in Helm to execute operations before the main install step.

Conclusion

Handling namespaces efficiently ensures that your applications can be deployed without issues related to resource separation in Kubernetes. By leveraging Helm templates and Kubernetes hooks, you can create namespaces dynamically within your Helm charts, ensuring the environment is always set up correctly for your deployments.


Course illustration
Course illustration

All Rights Reserved.