쿠버네티스

[클라우드] 12.Kubernetes Helm 사용하기

트리스탄1234 2023. 8. 22. 05:35
728x90
반응형

Helm Ovierview

쿠버네티스에서는 Helm이라고 하는 Package Managing Tool이 있습니다. 이 툴은 node.js의 npm과 유사하게 Kuberentes의 Package를 배포 가능하게 하는 Tool 입니다. 이 Helm의 구조를 보면 아래와 같습니다.

Helm은 Chart 라고 부르는 Package Format을 사용하게 되는데, 이 Chart는 Kubernetes의 Resource들을 정의하는 파일들의 집합입니다. yaml + templates = helm이라고 생각을 하시면 될것 같습니다.

Helm에서는 Packing된 아카이브를 helm chart라 부릅니다. helm chart는 templates과 value.yaml파일로 구성이 되는데 . 이 두개의 조합으로 하나의 패키지를 만들어 쿠버네티스 클러스터 상에 배포가 되게 됩니다.

Helm을 통해 할수 있는 일을 보면 아래와 같습니다.

  • 새로운 Chart를 생성 가능
  • Chart들을 통해 Chart 아카이프 (tgz) 파일을 생성할 수 있습니다.
  • Chart들이 저장된 Repositories와 상호작용(가져오기 등)을 할 수 있습니다.
  • Chart들을 Kubernetes Cluster에 설치/제거 할 수 있습니다.
  • Helm을 통해 설치된 Chart들에 대한 Release Cycle을 관리할 수 있습니다.

그럼 이제 Helm을 구성하는 3가지 개념을 살펴 봅시다.

  • Chart : Helm의 package 이며, Kubernetes Cluster에서 application, service 등을 동작 시키는 resource들을 포함하고 있음
  • Repository : Chart (Kubernetes Package) 들이 모아지고, 공유되는 저장소
  • Release : Chart의 Instance이며, 하나의 Chart는 동일한 Cluster에 여러번 설치될 수 있고, 각각 설치될 때마다 새로운 release 가 생성

Chart 의 내부 구조

Charts

Chart는 디렉토리 내부에 파일들으로 구성이 되고. 디렉토리 이름이 Chart의 이름이 됩니다.

예를들어, WordPress라는 Chart는 wordpress/ 디렉토리에 저장이 되고, 그 구조는 아래와 같습니다.

wordpress/
Chart.yaml # A YAML file containing information about the chart
LICENSE # OPTIONAL: A plain text file containing the license for the chart
README.md # OPTIONAL: A human-readable README file
values.yaml # The default configuration values for this chart
values.schema.json # OPTIONAL: A JSON Schema for imposing a structure on the values.yaml file
charts/ # A directory containing any charts upon which this chart depends.
crds/ # Custom Resource Definitions
templates/ # A directory of templates that, when combined with values,
# will generate valid Kubernetes manifest files.
templates/NOTES.txt # OPTIONAL: A plain text file containing short usage notes

Helm 은 Chart/ 디렉토리와 templates/ 디렉토리와 지정된 파일명을 사용을 합니다.

그럼 chart.yaml 파일에 대해서 알아 봅시다. chart.yamll파일은 chart의 필수적인 파일 입니다.

그 내용을 보면 아래와 같습니다.

Chart.yaml 파일의 구성 요소

apiVersion: The chart API version (required)
name: The name of the chart (required)
version: A SemVer 2 version (required)
kubeVersion: A SemVer range of compatible Kubernetes versions (optional)
description: A single-sentence description of this project (optional)
type: The type of the chart (optional)
keywords:
- A list of keywords about this project (optional)
home: The URL of this projects home page (optional)
sources:
- A list of URLs to source code for this project (optional)
dependencies: # A list of the chart requirements (optional)
- name: The name of the chart (nginx)
version: The version of the chart ("1.2.3")
repository: (optional) The repository URL ("https://example.com/charts") or alias ("@repo-name")
condition: (optional) A yaml path that resolves to a boolean, used for enabling/disabling charts
tags: # (optional)
- Tags can be used to group charts for enabling/disabling together
import-values: # (optional)
- ImportValues holds the mapping of source values to parent key to be imported. Each item can be a string or
pair of child/parent sublist items.
alias: (optional) Alias to be used for the chart. Useful when you have to add the same chart multiple times
maintainers: # (optional)
- name: The maintainers name (required for each maintainer)
email: The maintainers email (optional for each maintainer)
url: A URL for the maintainer (optional for each maintainer)
icon: A URL to an SVG or PNG image to be used as an icon (optional).
appVersion: The version of the app that this contains (optional). Needn't be SemVer. Quotes recommended.
deprecated: Whether this chart is deprecated (optional, boolean)
annotations:
example: A list of annotations keyed by name (optional).

Templates 파일

Helm Chart의 Template들은 Go template language로 작성이 되고, 다양한 template funtion들을 제공 합니다. 이런 Template 파일들은 Chart의 template/ 디렉토리에 저장됩니다. Helm이 Chart를 Rendering할 때, 해당 디렉토리 내의 모든 파일들이 template engine으로 전달이 됩니다.

Template이 사용하는 Value들은 두가지 방법에 의해 전달이 가능합니다. 그 방법은 아래와 같습니다.

  • Chart 개발자가 values.yaml파일을 사용하는 경우, chart 내에 포함시켜 제공, 이 파일은 default value를 포함하고 있습니다.
  • Chart 사용자가 별도의 yaml파일을 사용하는 경우, helm install 명령을 통해 사용합니다.

만약 사용자가 custom value를 사용하는 경우, 이 value는 chart 내에 있는 values.yaml의 value를 override 합니다.

그럼 templates 파일의 예를 살펴 보겠 습니다.

apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "sample.fullname" . }}
labels:
{{- include "sample.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include "sample.selectorLabels" . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "sample.selectorLabels" . | nindent 8 }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "sample.serviceAccountName" . }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: {{ .Chart.Name }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- name: http
containerPort: 80
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}

value.yaml 파일 살펴 보기

그럼 이제 value.yaml 파일을 살펴 보겠 습니다. 아래는 value.yaml 파일의 예입니다.

# Default values for sample.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
replicaCount: 1
image:
repository: nginx
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: ""
imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""
serviceAccount:
# Specifies whether a service account should be created
create: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name: ""
podAnnotations: {}
podSecurityContext: {}
# fsGroup: 2000
securityContext: {}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000
service:
type: ClusterIP
port: 80
ingress:
enabled: false
className: ""
annotations: {}
# kubernetes.io/ingress.class: nginx
# kubernetes.io/tls-acme: "true"
hosts:
- host: chart-example.local
paths:
- path: /
pathType: ImplementationSpecific
tls: []
# - secretName: chart-example-tls
# hosts:
# - chart-example.local
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi
autoscaling:
enabled: false
minReplicas: 1
maxReplicas: 100
targetCPUUtilizationPercentage: 80
# targetMemoryUtilizationPercentage: 80
nodeSelector: {}
tolerations: []
affinity: {}

이런 기본 value.yaml에서 제공하는 값 말고 별도의 값을 사용하고 싶으면 별도의 yaml 파일을 만들어 chart를 설치할때 사용을 하면 됩니다.

values.yaml 로 정의된 value들은 template 에서는 .Values object를 통해 접근 할 수 있습니다. 위의 예에서 service type은 .Values.service.type으로 접근 할 수 있습니다. Chart에 포함되는 values.yaml 파일의 이름은 변경할 수 없으며, helm 명령과 함께 지정할 수 있는 별도의 yaml 파일명은 어떤 것이든 생성 가능 합니다.

Helm 설치하기

Helm을 설치 하기 위해 Master Node에서 아래 명령을 통해 Helm을 설치 하고 설치된 버전을 확인 합니다.

root@master-VirtualBox:~# curl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 > get_helm.sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 11156 100 11156 0 0 38075 0 --:--:-- --:--:-- --:--:-- 38075
root@master-VirtualBox:~# chmod 700 get_helm.sh
root@master-VirtualBox:~# ./get_helm.sh
Verifying checksum... Done.
Preparing to install helm into /usr/local/bin
helm installed into /usr/local/bin/helm
root@master-VirtualBox:~# helm version
version.BuildInfo{Version:"v3.9.2", GitCommit:"1addefbfe665c350f4daf868a9adc5600cc064fd", GitTreeState:"clean", GoVersion:"go1.17.12"}

Helm 명령어 알아보기

우선 아래 명령을 사용해서 repositry를 추가해 줍니다.

root@master-VirtualBox:~# helm repo add bitnami https://charts.bitnami.com/bitnami
"bitnami" has been added to your repositories

두번째 명령어인 Helm search 명령어는 chart를 검색하기 위한 command 이며, 두가지 소스 유형을 검색할 수 있습니다.

  • helm search hub는 여러 저장소들에 있는 helm chart를 포괄하는 Artifact Hub에서 검색합니다.
  • helm search repo는 helm repo add를 사용하여 로컬 helm client에 추가된 저장소에서 검색합니다.

wordpress의 chart를 검색해 봅시다.

root@master-VirtualBox:~# helm search hub wordpress
URL CHART VERSION APP VERSION DESCRIPTION
https://artifacthub.io/packages/helm/kube-wordp... 0.1.0 1.1 this is my wordpress package
https://artifacthub.io/packages/helm/bitnami-ak... 15.0.14 6.0.1 WordPress is the world's most popular blogging ...
https://artifacthub.io/packages/helm/bitnami/wo... 15.0.14 6.0.1 WordPress is the world's most popular blogging ...
https://artifacthub.io/packages/helm/groundhog2... 0.6.2 6.0.1-apache A Helm chart for Wordpress on Kubernetes
https://artifacthub.io/packages/helm/riftbit/wo... 12.1.16 5.8.1 Web publishing platform for building blogs and ...
https://artifacthub.io/packages/helm/camptocamp... 0.6.10 4.8.1 Web publishing platform for building blogs and ...
https://artifacthub.io/packages/helm/mcouliba/w... 0.1.0 1.16.0 A Helm chart for Kubernetes

이제 검색한 chart들 중 하나를 설치해 보겠습니다. 사용 방법은 아래와 같습니다 .

helm install 'release명' 'chart명'

그럼 검색된 chart 중 하나를 설치해 보겠 습니다.

root@master-VirtualBox:~# helm install my-wordpress bitnami/wordpress
NAME: my-wordpress
LAST DEPLOYED: Tue Aug 9 13:55:08 2022
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
CHART NAME: wordpress
CHART VERSION: 15.0.14
APP VERSION: 6.0.1

helm을 통해 chart를 설치를 하면 바로 deploy가 진행이 됩니다.

생성된 resource들을 아래 명령을 통해 확인해 봅시다.

root@master-VirtualBox:~# kubectl get all
NAME READY STATUS RESTARTS AGE
pod/my-wordpress-64d77cb56f-nmvpw 0/1 Pending 0 2m47s
pod/my-wordpress-mariadb-0 0/1 Pending 0 2m47s
pod/wordpress-6cffd787fd-wws7s 0/1 CrashLoopBackOff 38 (4m11s ago) 20h
pod/wordpress-mysql-5b9c9bc7bb-2ps92 0/1 Pending 0 20h
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 4d20h
service/my-wordpress LoadBalancer 10.110.229.24 192.168.72.103 80:31992/TCP,443:30739/TCP 2m47s
service/my-wordpress-mariadb ClusterIP 10.105.114.217 <none> 3306/TCP 2m47s
service/wordpress NodePort 10.111.106.227 <none> 8080:30019/TCP 20h
service/wordpress-mysql ClusterIP None <none> 3306/TCP 20h
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/my-wordpress 0/1 1 0 2m47s
deployment.apps/wordpress 0/1 1 0 20h
deployment.apps/wordpress-mysql 0/1 1 0 20h
NAME DESIRED CURRENT READY AGE
replicaset.apps/my-wordpress-64d77cb56f 1 1 0 2m47s
replicaset.apps/wordpress-6cffd787fd 1 1 0 20h
replicaset.apps/wordpress-mysql-5b9c9bc7bb 1 1 0 20h
NAME READY AGE
statefulset.apps/my-wordpress-mariadb 0/1 2m47s
root@master-VirtualBox:~#

helm을 통해 설치된 package를 삭제를 하려면 아래의 명령을 사용해서 삭제를 하면 됩니다.

root@master-VirtualBox:~/wordpress# helm uninstall my-wordpress
release "my-wordpress" uninstalled

upgrade를 할때에는 helm upgrade명령을 사용하여 업데이트를 하면 됩니다.

나만의 chart를 생성하고 싶은 경우에는 아래와 같이 create 명령을 하고 필요한 파일을 수정 후 helm install을 이용해 설치를 진행 하면 됩니다.

oot@master-VirtualBox:~/wordpress# helm create mychart
root@master-VirtualBox:~/wordpress# tree mychart/
mychart/
├── charts
├── Chart.yaml
├── templates
│ ├── deployment.yaml
│ ├── _helpers.tpl
│ ├── hpa.yaml
│ ├── ingress.yaml
│ ├── NOTES.txt
│ ├── serviceaccount.yaml
│ ├── service.yaml
│ └── tests
│ └── test-connection.yaml
└── values.yaml

생성된 chart가 제대로 작성이 되었는지 오류가 없는지 검사하기 위해 helm lint 명령을 사용을 하여 검사하면 됩니다.

root@master-VirtualBox:~/wordpress# helm lint mychart/
==> Linting mychart/
[INFO] Chart.yaml: icon is recommended
1 chart(s) linted, 0 chart(s) failed

helm template은 template엔진에게 templates 디렉토리에 있는 template파일(deployment.yaml, service.yaml, ingress.yaml 등)들, values.yaml과 templates/_helpers.tpl의 값을 참조하여 배포 manifest파일을 만들어 줍니다. 이 값을 확인해 보려면 아래의 명령을 사용하면 됩니다.

oot@master-VirtualBox:~/wordpress# helm template mychart/
---
# Source: mychart/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: release-name-mychart
labels:
app.kubernetes.io/name: mychart
app.kubernetes.io/instance: release-name
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
---
# Source: mychart/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: release-name-mychart
labels:
app.kubernetes.io/name: mychart
app.kubernetes.io/instance: release-name
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
spec:
type: ClusterIP
ports:
- port: 80
targetPort: http
protocol: TCP
name: http
selector:
app.kubernetes.io/name: mychart
app.kubernetes.io/instance: release-name
---
# Source: mychart/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: release-name-mychart
labels:
app.kubernetes.io/name: mychart
app.kubernetes.io/instance: release-name
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: mychart
app.kubernetes.io/instance: release-name
template:
metadata:
labels:
app.kubernetes.io/name: mychart
app.kubernetes.io/instance: release-name
spec:
serviceAccountName: release-name-mychart
securityContext:
{}
containers:
- name: mychart
securityContext:
{}
image: "nginx:1.16.0"
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{}
---
# Source: mychart/templates/tests/test-connection.yaml
apiVersion: v1
kind: Pod
metadata:
name: "release-name-mychart-test-connection"
labels:
app.kubernetes.io/name: mychart
app.kubernetes.io/instance: release-name
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
annotations:
spec:
containers:
- name: wget
image: busybox
command: ['wget']
args: ['release-name-mychart:80']
restartPolicy: Never
root@master-VirtualBox:~/wordpress#

helm package명령은 chart 디렉토리를 아카이브(압축) 합니다.

아카이브된 파일명은, Chart.yaml 파일의 'name_value'-'version_value'.tgz 으로 생성됩니다.

root@master-VirtualBox:~/wordpress# helm package ./mychart
Successfully packaged chart and saved it to: /root/wordpress/mychart-0.1.0.tgz

Chart 수정하기

chart의 값을 변경 하는 방법에는 2가지 방법이 있습니다.

  • value 변경 하기.
  • chart 수정하기

우선 기본값을 확인해 보겠습니다. 조회 하는 명령어 형식은 아래와 같습니다

helm show chart 'chart이름'

root@master-VirtualBox:~# helm show chart bitnami/wordpress
annotations:
category: CMS
apiVersion: v2
appVersion: 6.0.1
dependencies:
- condition: memcached.enabled
name: memcached
version: 6.x.x
- condition: mariadb.enabled
name: mariadb
version: 11.x.x
- name: common
tags:
- bitnami-common
version: 1.x.x
description: WordPress is the world's most popular blogging and content management
platform. Powerful yet simple, everyone from students to global corporations use
it to build beautiful, functional websites.
keywords:
- application
- blog
- cms
- http
- php
- web
- wordpress
maintainers:
- name: Bitnami
name: wordpress
sources:
version: 15.0.14

이제 값을 변경하는 방법을 알아 보겠습니다. 우선 값을 변경 하는 방법은 아래와 같이 2가지가 있습니다.

  • set 옵션을 이용하는 방법

helm template --name myrelease --set replicaCount=10 ./helloworld

  • --value 도는 -f 옵션 사용하는 방법

변경할 파라메터를 별도의 yaml파일에 전달 하고 install시 전달하는 방법입니다.

예를 들면 myval.yam 파일을 만들어 아래의 내용을 입력한 후에 아래 명령을 실행시키면 됩니다.

root@master-VirtualBox:~# vi myval.yaml
name: "fromValuefile"
root@master-VirtualBox:~#helm install -f myval.yaml --name newrelease --dry-run --debug ./helloworld

두번째로 chart를 수정하는 방법에 대해서 알아 보겠습니다.

chart를 수정해서 설치하려면, repository로 부터 chart를 다운받아서 수정을 하고 수정된 chart를 가지고 helm 설치를 할 수 있습니다.

그럼 우선 chart를 download 해봅시다.

root@master-VirtualBox:~# helm pull --untar bitnami/wordpress
root@master-VirtualBox:~# cd wordpress/
root@master-VirtualBox:~/wordpress# ls -al
total 152
drwxr-xr-x 4 root root 4096 8월 9 14:46 .
drwx------ 11 root root 4096 8월 9 14:46 ..
-rw-r--r-- 1 root root 387 8월 9 14:46 Chart.lock
drwxr-xr-x 5 root root 4096 8월 9 14:46 charts
-rw-r--r-- 1 root root 1048 8월 9 14:46 Chart.yaml
-rw-r--r-- 1 root root 333 8월 9 14:46 .helmignore
-rw-r--r-- 1 root root 65916 8월 9 14:46 README.md
drwxr-xr-x 2 root root 4096 8월 9 14:46 templates
-rw-r--r-- 1 root root 5706 8월 9 14:46 values.schema.json
-rw-r--r-- 1 root root 46579 8월 9 14:46 values.yaml

값을 변경하려면 value.yaml파일을 수정하고, templates를 변경하려면 teplates 디렉토리에서 수정을 하면됩니다. 필요한 파일을 수정한 후 helm install명령을 통해서 설치를 하면 됩니다.

728x90
반응형