Helm является менеджером пакетов Kubernetes и используется для управления приложениями Kubernetes. С помощью Helm вы можете определить, установить и обновить приложение Kubernetes. Его можно использовать для воспроизводимых сборок вашего приложения Kubernetes. Это как apt / yum / homebrew для Kubernetes.
Чтобы использовать Helm, у вас должен быть установлен Kubernetes для использования диаграмм Helm, и вы должны иметь знания о Kubernetes.
Установка шлема
Разные способы установки Helm
- Загрузите двоичные файлы отсюда в зависимости от вашей ОС и добавьте Helm к пути или перейдите в папку, содержащую Helm в терминале
- Использование менеджеров пакетов
MacOS :
Оболочка
xxxxxxxxxx
1
$ brew install helm
Windows :
Используя Chocolatey :
Оболочка
xxxxxxxxxx
1
> choco install kubernetes-helm
Оболочка
xxxxxxxxxx
1
$ curl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash
Вы можете проверить успешную установку Helm, используя следующую команду на терминале:
Оболочка
xxxxxxxxxx
1
$ helm version
Эта команда выдаст вам версию Helm в следующем формате:
Оболочка
xxxxxxxxxx
1
version.BuildInfo{Version:”v3.0.2", GitCommit:”19e47ee3283ae98139d98460de796c1be1e3975f”, GitTreeState:”clean”, GoVersion:”go1.13.5"}
2
Инициализировать диаграммы шлема
Диаграммы - это формат упаковки, используемый в Helm. Диаграмма - это совокупность нескольких файлов, папок и шаблонов для определения нескольких ресурсов Kubernetes. Шаблоны являются определениями ресурсов Kubernetes, и вы можете использовать одну и ту же диаграмму для нескольких разных выпусков, вставляя свои динамические значения в шаблон. Шаблон состоит из различных директив, и вы можете настроить их в зависимости от ваших потребностей и ввести значения, которые являются уникальными для вашего выпуска. Таким образом, вы можете повторно использовать одну и ту же диаграмму для всех ваших выпусков, вставляя в шаблон динамические значения, которые относятся к вашему выпуску, например, имя образа Docker, количество реплик этого экземпляра и так далее.
Вам также может понравиться: Развертывание в Куберне с Хелмом
Вы можете инициализировать репозиторий Helm Chart с официальным репозиторием Helm Chart или любым другим репозиторием, добавив различные доступные репозитории Helm Chart:
xxxxxxxxxx
1
$ helm repo add stable https://kubernetes-charts.storage.googleapis.com/
Вы можете обновить вышеуказанное репо для изменений, используя:
Оболочка
xxxxxxxxxx
1
$ helm repo update
2
Вы можете перечислить все стабильные графики, доступные в вышеуказанном репозитории, используя команду ниже, вы можете использовать любой график из них в качестве базового графика:
xxxxxxxxxx
1
$ helm search repo stable
Шлем
Helm используется для установки и управления приложениями в Kubernetes, поэтому для использования Helm должен быть запущен кластер Kubernetes. Вы можете использовать одноузловой кластер Minikube для Kubernetes на локальном компьютере или запустить одноузловой кластер Kubernetes из Docker для настольных компьютеров . Если вы используете рабочий стол Docker в Windows, вы можете щелкнуть правой кнопкой мыши значок Docker на панели задач и перейти к настройкам, а затем перейти к Kubernetes и включить Kubernetes при запуске рабочего стола Docker. Это активирует одноузловой кластер Kubernetes, и вы можете проверить с помощью следующей команды:
Оболочка
xxxxxxxxxx
1
$ kubectl version
(Откройте новый терминал после включения Kubernetes)
Хелм Чартс
Диаграмма Хелма содержит все определения всех ресурсов, необходимых для запуска приложений в Kubernetes. Он содержит шаблоны определений для развертывания, обслуживания, входа и т. Д. Хранилище - это место, где хранятся все опубликованные диаграммы. Вы можете добавить несколько репозиториев в Helm, как мы это делали ранее в этом уроке.
Релиз является экземпляром диаграммы, и новая версия создается при установке любой диаграммы. С каждой установкой диаграммы будет создаваться новый выпуск с другим названием выпуска.
Хелм устанавливает ресурсы Kubernetes, доступные в определенной диаграмме, в кластер Kubernetes.
Поиск в чартах
Есть два способа найти диаграммы, один из общедоступного центра Helm, который содержит диаграммы из нескольких репозиториев. Вы можете выполнить поиск в Helm hub с помощью приведенной ниже команды, указав полное или частичное имя диаграммы, которую хотите найти, и эта команда выведет список всех соответствующих диаграмм с этим именем. Например, если вы хотите найти диаграмму MySQL
Оболочка
xxxxxxxxxx
1
$ helm search hub mysql
Другой способ - искать в репозиториях, которые вы уже добавили в Helm. Сначала вы можете перечислить все репо, добавленные вами в Helm, используя следующую команду, в которой будут перечислены все репо, настроенные в вашем шлеме.
Оболочка
xxxxxxxxxx
1
$ helm repo list
2
Для поиска во всех репозиториях, перечисленных вышеупомянутой командой, вы можете использовать эту команду:
xxxxxxxxxx
1
$ helm search repo mysql
Helm Install
You can install any Helm chart from the list provided by the Helm repositories.
xxxxxxxxxx
$ helm install <release-name> <chart-name>
Here, release-name
is optional. It is the name you want to give to your release and if you don’t provide the release-name
then you have to provide an another flag “— generate-name
”, then Helm automatically chooses release name for you and will print in the outcome of this command. The second option is the chart name. It is the name of the chart you want to install and you can find this name by searching on Helm hub or in configured repositories.
This command will create a new release with the name provided and install it on the Kubernetes cluster which means a new MySQL instance will be released on the Kubernetes cluster if you install a MySQL chart. If you want to release two MySQL databases, then install MySQL chart twice. It will release various resources like deployment pod, services, ingress and more, which are present in that chart to Kubernetes cluster. You can use any Kubernetes kubectl commands ( kubectl get pods — —
to list all the released pods in Kubernetes cluster) to list the pods or you can use Helm commands to list releases. This is similar to installing all resources to Kubernetes one by one using kubectl APIs.
You can see all your releases with
xxxxxxxxxx
$ helm list
By installing using above command you are releasing default charts. If you want to modify the config, you can use the below command which will list all the configurations of that chart and you can modify any variable by providing a YAML formatted file during installation.
xxxxxxxxxx
$ helm show values stable/mysql
This will list down all the configuration and you can modify any by:
xxxxxxxxxx
$ echo '{mysqlPassword: admin, mysqlUser: admin}' > test.yaml $ helm install -f test.yaml stable/mysql
You can also use the “ — set
” flag instead of “ f-f
” for modifying variables on command line by providing multiple variables separated by comma. For example,
xxxxxxxxxx
$ helm install --set mysqlPassword=admin,mysqlUser=admin stable/mysql
So by Helm install, you can release all the resources available on chart definition on one go. If you want the same configuration to be repeated you can publish your charts and anyone can use that chart to release with the similar configuration on Kubernetes.
Helm Upgrade and Rollback
When you want to change the configuration of an existing release, then you can use the Helm upgrade command. This command will be used to update an existing release based on the new configuration you provide. Helm will only update those resources which are modified according to new config and left other resources in release unchanged. In this new config YAML file, you can update the value to any variable, you can provide a new Docker image or tag if you want to update release with newer image.
xxxxxxxxxx
$ helm upgrade -f newConfig.yaml <release-name> <chart-name>
You can list down all the values and check whether your new values are applied to release or not
xxxxxxxxxx
$ helm get values <release-name>
If something goes wrong and you want to roll back to some earlier version then it is very simple. You can first check the history of your releases by using the history command and, after choosing the right rollback revision from the history, you can rollback to that particular release using thesecommands:
xxxxxxxxxx
$ helm history <release-name> $ helm rollback <release-name> <release-version-number>
The release version number is the number corresponding to the release to which you want to rollback. The release number will have an increment of 1 every time you upgrade or rollback a release starting from one when you first install a release.
The Helm install command will finish without waiting for pods to come up, but if you want the command to wait for pods to come up and service to have an IP address then you can use below flag while installing
xxxxxxxxxx
--wait
You can also use timeout duration in seconds and the release will fail if Helm takes longer time while waiting for release to finish in Kubernetes cluster:
xxxxxxxxxx
--timeout=300
Helm Uninstall
If you want to uninstall a release from Kubernetes you can use Helm to uninstall it. By default Helm doesn’t keep the history of any uninstalled release.
xxxxxxxxxx
$ helm uninstall <release-name>
If you want to keep a history of any uninstalled release then you can do so by below flag while uninstalling
xxxxxxxxxx
$ helm uninstall --keep-history <release-name>
Using the “uninstalled” flag in the Helm list command, you can see all releases which were uninstalled using “keep history” flag and you can also use “all” flag to list all releases whether active or uninstalled with the “keep history” flag.
xxxxxxxxxx
$ helm list --uninstalled $ helm list --all
Create Your Own Chart
We've been working on predefined charts provided by Helm hub, but what if we want to create our own chart? To create your own chart Helm, provide a utility that will initialize your basic structure of chart.
xxxxxxxxxx
$ helm create customchart
This will create a folder named "customchart" and that folder will have below structure:
xxxxxxxxxx
customchart/ .helmignore Chart.yaml values.yaml charts/ templates/
Chart.yaml contains a description about the chart.
"charts/ folder" can contains other sub-charts and this folder is empty by default.
"values.yaml" is the YAML file that contains key-value pairs for the default values for the release configuration. It contains values for replicacount
(number of pods you want to instantiate in Kubernetes), image name, resource configurations (memory and CPU limits). You can override them by providing your custom config YAML file at the time of Helm install or upgrade as we discussed earlier while working with predefined charts.
"templates/ folder" contains multiple template files for deployment, services, ingress, etc. Helm evaluates all the template file by template rendering engine by combining them with default config values provided or with the custom values provided at the time of install. You can consider these files as static templates to Kubernetes resources which accepts dynamic values like docker image name, the number of replicas of any pod needed, etc. from values.yaml or at runtime and provide the resultant resource file to Kubernetes.
Deployment template in charts is a YAML file for deployment of a pod in Kubernetes. It is a template and accepts a Docker image name, replica count and other details related to pod deployment.
Service template is for setting up a service resource in Kubernetes which is used to allow load balancing between multiple pods of similar functionality and defines a policy by which to access pods. Service resource uses a selector to target a particular set of pods only. Selectors are nothing but the labels defined in pod deployments.
Ingress template is a template for ingress. Ingress helps to route HTTP and HTTPS requests from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.
You can delete all the templates and create your own from scratch as well only for the Kubernetes resources you want to release. You can install the above chart by navigating to the directory containing chart folder in terminal and by using the below command to install everything present in that chart. This will create a new release in Kubernetes based on all the configuration provided in the chart.
xxxxxxxxxx
$ helm install ./customchart
It will assign a name for a Kubernetes release and will show you this name in the outcome of the above command. You can check the actual template for each Kubernetes resources which are released on Kubernetes by using below command with the release name.
xxxxxxxxxx
$ helm get manifest <release-name>
You can uninstall any release by the same release name using below command.
xxxxxxxxxx
$ helm uninstall <release-name>
When you provide name of any resource in template file, consider it to be a unique. To make it unique you can append the name of the release along with the resource type to make it unique in Kubernetes cluster. This name field in Kubernetes is restricted to 63 characters only, so plan your release name accordingly.
xxxxxxxxxx
name: {{ .Release.Name }}-deployment
You can use any template directive by enclosing it in
{{
and}}
blocks
The above template directive will inject a name of release and append “ -deployment
” after it to make a name of a deployment resource in deployment template. “ Release
” object is a built in object in Helm and we are accessing “ Name
” from that object by using “ .
” operator. The initial “ .
” before “Release
” signifies that this is a top-level object.
You can use any value from values.yaml file by using {{ .Values.fieldname }}
directive in template file to inject any dynamic value into template.
Sometimes you are not sure what this template will become after rendering, so you can use the “debug
” flag to just see the final template without installing anything to Kubernetes. You can use below command and this command will not install anything to the Kubernetes but will print final template after Helm rendering and injecting values into template.
xxxxxxxxxx
$ helm install --debug --dry-run ./customchart
If you want to use a single command for upgrade and install, which means install a release with this name if not already exists and upgrade otherwise using single command then you can use, — install
flag, which directs Helm that if a release by this name doesn’t already exist, run an install, you can also use — force flag to replace any failed release.
xxxxxxxxxx
$ helm upgrade --install --force <release-name> ./customchart
You can check various directives and built-in objects in Helm and practice by creating your own charts or follow the auto-generated templates by Helm for basic structure of Helm release templates.
Further Reading
The Art of the Helm Chart: Patterns from the Official Kubernetes Chart