Deployment automation to Kubernetes with Gitlab and Helm
In the previous post, I gave a brief instruction on how to deploy to Kubernetes using kubectl
tool. This might be sufficient for a small set of resources but what if there is a need to deploy multiple resources and replace many variables, the script
section would become cumbersome. In this article, I’ll introduce using Helm for processing templates of the configuration.
Creating a helm chart
helm create mynginx
rm ./mynginx/templates/*
- create
./mynginx/templates/deployment.yaml
:
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ .Release.Name }}-deployment
labels:
app: {{ .Values.app }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app: {{ .Values.app }}
template:
metadata:
labels:
app: {{ .Values.app }}
spec:
containers:
- name: {{ .Values.app }}
image: "{{ .Values.image }}:{{ .Values.version }}"
ports:
- containerPort: 80
env:
- name: ENV
value: {{ .Values.env }}
- create
./mynginx/templates/NOTES.txt
:
Thank you for installing {{ .Chart.Name }}.Your release is named {{ .Release.Name }}.To learn more about the release, try:$ helm status {{ .Release.Name }}
$ helm get all {{ .Release.Name }}
- create
./mynginx/values.yaml
replicaCount: 1app: my-nximage: zjor/my-nxenv: prod
Let’s make it visible that something is changing at runtime when we provide values to the configuration. Change Dockerfile
as follows:
FROM nginx
COPY html /usr/share/nginx/htmlCMD ["bash", "-c", "echo \"ENV=${ENV}\" && nginx -g \"daemon off;\""]
Change .gitlab-ci.yml to deploy with helm
deploy_with_helm:
stage: deploy
image: dtzar/helm-kubectl
script:
- kubectl config set-cluster k8s --server="${SERVER}"
- kubectl config set clusters.k8s.certificate-authority-data ${CERTIFICATE_AUTHORITY_DATA}
- kubectl config set-credentials gitlab --token="${USER_TOKEN}"
- kubectl config set-context default --cluster=k8s --user=gitlab
- kubectl config use-context default
- helm upgrade --install mynginx-release ./mynginx --set version=${CI_COMMIT_SHORT_SHA}
only:
- feature/helm
Apparently kubectl
changes the context so that helm can authorize in the cluster.