Kubernetes (k8s) + Helm + GitLab CI / CD. Properly deployed

  • Tutorial
In this article I want to tell how to deploy applications in different environments. In this example, we will deploy to: “Test” and “Production”. Of course, you can add any media.

For application deployment I use HELM. It allows flexible configuration management. What you can see below. It is assumed that you already have a tuned runner with helm and you know and know how to work with HELM.

Example file: .gitlab-ci.yml

.base_deploy: &base_deploy
  stage: deploy
  script:
  - PROJECT_NAME="${CI_PROJECT_NAME}-${CI_ENVIRONMENT_SLUG}"
  - helm --namespace ${CI_ENVIRONMENT_SLUG} upgrade -i ${PROJECT_NAME} helm --set"global.env=${CI_ENVIRONMENT_SLUG}";
stages:
  - deploy
Deploy to Test:
  <<: *base_deploy
  environment:
    name: test
Deploy to Production:
  <<: *base_deploy
  environment:
    name: production
  when: manual

Here you should pay attention to the fact that, depending on the environment, we are passing a variable: “test” or “production”.

We also form the name of the project taking into account the name of the variable, so that helm understands that these are different projects (helm ls).

Next, we pass this variable (environment) to the HELM as: “global.env”.

For the above example, helm should be in the same folder in your repository.

Now consider an example of how to use the environment variable in HELM Chart-ah.

Create the following values.yaml :

replicas:
  test: 1
  production: 3
domain:
  test: test.domain.com
  production: production.domain.com
resources:
  requests:
    cpu:
      _default: 50m
      production: 50m
    memory:
      _default: 256Mi
      production: 10Mi
  limits:
    memory:
      _default: 1Gi
      production: 1Gi
    cpu:
      _default: 1000m

Here you can see that for different environments we specify different settings.
For convenience, you can specify the default settings.

Another example for ingress.yaml:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{ .Chart.Name }}
spec:
  rules:
  - host: {{ pluck .Values.global.env .Values.domain | first | default .Values.domain._default }}
    http:
      paths:
      - path: /
        backend:
          serviceName: {{ .Chart.Name }}
          servicePort: 80

You can always check how your Chart is going, with the command:

helm template ./helm --set"global.env=test"
helm template ./helm --set"global.env=production"

You can also deploy your code to different nodes depending on the environment.

Example:

{{ if eq .Values.global.env"test" }}
      nodeSelector:
        nodetype: testnodes
{{ elseif eq .Values.global.env"production" }}
      nodeSelector:
        nodetype: productionnodes
{{ else }}

Thanks to all. Deployte right.

Also popular now: