티스토리 뷰

Cloud/Docker & Kubernetes

[Kubernetes] Helm 사용법

Reo Dongmin Lee 2019. 1. 16. 02:36




Helm 이란?

Helm 은 쿠버네티스 package managing tool 이다. node.js 의 npm 과 비슷한 형태로 쿠버네티스 패키지 배포를 가능하게 하는 tool 이라고 보면 된다.

chart 라고 부르는 package format을 사용하는데 chart는 쿠버네티스 리소스를 describe 하는 파일들의 집합이다.

특정 directory 하위에 모여있는 파일들을 통틀어서 chart라고 부르는데 좀 더 쉽게 예를들면, 가령 WordPress chart는 다음과 같은 구조를 가진다.

wordpress/ derectory 밑으로

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
      requirements.yaml        # OPTIONAL: A YAML file listing dependencies for the chart
      values.yaml              # The default configuration values for this chart
      charts/                  # A directory containing any charts upon which this chart depends.
      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

위와 같은 구조로 되어 있고 version 정보가 붙어서 tgz 형태로 압축 패키징 된다.

가령 1.2.3 version의 nginx chart는 nginx-1.2.3.tgz 이런식으로.

Chart 에 대한 더 자세한 설명은 Helm Doc-charts를 참고한다.



Helm은 크게 client와 server(tiller). 이렇게 두가지 파트로 나뉘어져있다.

client는 end user를 위한 command line client이고 주로 local chart 개발이나 repository managing, server(tiler)에 chart 설치 요청등 주로 chart를 관리하는 파트이고

Tiller라고도 부르는 server는 in-cluster 서버로 chart의 배포, 릴리즈를 관리하는 파트이다.

좀더 자세한 내용은 Helm Doc-Architecture 참고.




Helm 사용법

앞으로 설명할 사용법은 Google Cloud 에서 제공하는 qwiklabs 강의(Helm Package Manager)와 Helm 공식 사이트 documentation 을 참고하였다.

Helm 설치


실제 helm을 설치한후 쿠버네티스 패키지를 다운받아 릴리즈 해보자.

일단 helm을 설치하려면 쿠버네티스 cluster 가 미리 셋팅 되어야 한다.

요즘 Google 스터디잼으로 얻은 한달 qwiklabs 무료 쿠폰이 있어서 Google Cloud Platform(GCP) 환경에서 테스트 환경을 구축했다.

쿠버네티스 cluster 가 준비 되었다면 다음의 명령어로 설치 script를 다운받고 실행한다.

$ curl https://raw.githubusercontent.com/helm/helm/master/scripts/get > get_helm.sh
$ chmod 700 get_helm.sh
$ ./get_helm.sh

설치가 완료되면 helm 을 초기화하고 tiller를 설치할건데 그전에 tiller 서비스 account를 생성하고 cluster-admin role을 부여한다.

kubectl -n kube-system create sa tiller


kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller

helm도 설치하고 service account도 만들었으니 다음의 명령어로 Tiller를 설치해준다.

helm init --service-account tiller


만약 init 관련 flag 옵션들을 보려면 다음 명령어를 실행한다.

helm init --help



Chart 설치


최신 chart 리스트를 업데이트 하기 위해 다음 명령어를 실행한다.

helm repo update


설치 가능한 chart 목록을 보려면 helm search 명령어를 실행한다.

$ helm search
NAME                                    CHART VERSION   APP VERSION                     DESCRIPTION
stable/acs-engine-autoscaler            2.2.2           2.1.1                           DEPRECATED Scales worker nodes within agent pools
stable/aerospike                        0.2.1           v3.14.1.2                       A Helm chart for Aerospike in Kubernetes
stable/airflow                          0.12.0          1.10.0                          Airflow is a platform to programmatically author, schedul...
stable/anchore-engine                   0.10.0          0.3.1                           Anchore container analysis and policy evaluation engine s...
stable/apm-server                       0.1.0           6.2.4                           The server receives data from the Elastic APM agents and ...
stable/ark                              1.2.5           0.9.1                           A Helm chart for ark
stable/artifactory                      7.3.1           6.1.0                           DEPRECATED Universal Repository Manager supporting all ma...
stable/artifactory-ha                   0.4.1           6.2.0                           DEPRECATED Universal Repository Manager supporting all ma...
stable/atlantis                         1.1.1           v0.4.11                         A Helm chart for Atlantis https://www.runatlantis.io
stable/auditbeat                        0.4.2           6.5.4                           A lightweight shipper to audit the activities of users an...
stable/aws-cluster-autoscaler           0.3.3                                           Scales worker nodes within autoscaling groups.
stable/bitcoind                         0.1.4           0.15.1                          Bitcoin is an innovative payment network and a new kind o...
stable/bookstack                        1.0.0           0.24.3                          BookStack is a simple, self-hosted, easy-to-use platform ...
stable/buildkite                        0.2.4           3                               DEPRECATED Agent for Buildkite
stable/burrow                           1.0.1           0.23.3                          Burrow is a permissionable smart contract machine
stable/centrifugo                       3.1.0           2.1.0                           Centrifugo is a real-time messaging server.
stable/cerebro                          0.5.2           0.8.1                           A Helm chart for Cerebro - a web admin tool that replaces...
stable/cert-manager                     v0.5.2          v0.5.2                          A Helm chart for cert-manager
stable/chaoskube                        0.13.0          0.11.0                          Chaoskube periodically kills random pods in your Kubernet...
stable/chartmuseum                      1.8.4           0.8.1                           Host your own Helm Chart Repository
stable/chronograf                       1.0.0           1.7                             Open-source web application written in Go and React.js th...
stable/cloudserver                      1.0.0           8.1.1                           An open-source Node.js implementation of the Amazon S3 pr...
stable/cluster-autoscaler               0.11.1          1.13.1                          Scales worker nodes within autoscaling groups.
stable/cockroachdb                      2.0.9           2.1.3                           CockroachDB is a scalable, survivable, strongly-consisten...
stable/concourse                        3.5.1           4.2.2                           Concourse is a simple and scalable CI system.
stable/consul                           3.5.1           1.0.0                           Highly available and distributed service discovery and ke...
stable/coredns                          1.2.4           1.3.1                           CoreDNS is a DNS server that chains plugins and provides ...

...
...

꽤 많다.

원하는 chart가 있는지 직접 이름을 넣어서 검색해보자


$ helm search mysql
NAME                                    CHART VERSION   APP VERSION     DESCRIPTION
stable/mysql                            0.13.0          5.7.14          Fast, reliable, scalable, and easy to use open-source rel...
stable/mysqldump                        2.0.2           2.0.0           A Helm chart to help backup MySQL databases using mysqldump
stable/prometheus-mysql-exporter        0.2.1           v0.11.0         A Helm chart for prometheus mysql exporter with cloudsqlp...
stable/percona                          0.3.4           5.7.17          free, fully compatible, enhanced, open source drop-in rep...
stable/percona-xtradb-cluster           0.6.1           5.7.19          free, fully compatible, enhanced, open source drop-in rep...
stable/phpmyadmin                       2.0.3           4.8.4           phpMyAdmin is an mysql administration frontend
stable/gcloud-sqlproxy                  0.6.1           1.11            DEPRECATED Google Cloud SQL Proxy
stable/mariadb                          5.4.2           10.1.37         Fast, reliable, scalable, and easy to use open-source rel...


mysql로 검색했는데 꽤 여러가지 chart 가 나온다. 막 mariadb도 있고..

이유는 chart description에 mysql을 키워드로 등록해놨기 때문이다. 다음 명령어로 description 상세보기를 해보자.


helm inspect stable/mariadb



appVersion: 10.1.37
description: Fast, reliable, scalable, and easy to use open-source relational database
  system. MariaDB Server is intended for mission-critical, heavy-load production systems
  as well as for embedding into mass-deployed software. Highly available MariaDB cluster.
engine: gotpl
home: https://mariadb.org
icon: https://bitnami.com/assets/stacks/mariadb/img/mariadb-stack-220x234.png
keywords:
- mariadb
- mysql
- database
- sql
- prometheus
...
...


원래 mysql chart를 설치하려 했는데 기왕 이렇게 된거 mariadb chart를 설치해보자.


$ helm install stable/mariadb
NAME:   jaunty-ostrich
LAST DEPLOYED: Wed Jan 16 01:28:59 2019
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/Secret
NAME                    TYPE    DATA  AGE
jaunty-ostrich-mariadb  Opaque  2     1s

==> v1/ConfigMap
NAME                           DATA  AGE
jaunty-ostrich-mariadb-master  1     1s
jaunty-ostrich-mariadb-slave   1     1s
jaunty-ostrich-mariadb-tests   1     1s

==> v1/Service
NAME                          TYPE       CLUSTER-IP     EXTERNAL-IP  PORT(S)   AGE
jaunty-ostrich-mariadb        ClusterIP  10.39.251.181  <none>       3306/TCP  1s
jaunty-ostrich-mariadb-slave  ClusterIP  10.39.244.243  <none>       3306/TCP  1s

==> v1beta1/StatefulSet
NAME                           DESIRED  CURRENT  AGE
jaunty-ostrich-mariadb-master  1        1        1s
jaunty-ostrich-mariadb-slave   1        1        1s

==> v1/Pod(related)
NAME                             READY  STATUS   RESTARTS  AGE
jaunty-ostrich-mariadb-master-0  0/1    Pending  0         1s
jaunty-ostrich-mariadb-slave-0   0/1    Pending  0         1s


NOTES:

Please be patient while the chart is being deployed

Tip:

  Watch the deployment status using the command: kubectl get pods -w --namespace default -l release=jaunty-ostrich

Services:

  echo Master: jaunty-ostrich-mariadb.default.svc.cluster.local:3306
  echo Slave:  jaunty-ostrich-mariadb-slave.default.svc.cluster.local:3306

Administrator credentials:

  Username: root
  Password : $(kubectl get secret --namespace default jaunty-ostrich-mariadb -o jsonpath="{.data.mariadb-root-password}" | base64 --decode)

To connect to your database:

...
...


mariadb 가 잘 설치되었다. 설치 로그를 보면 install 명령어로 chart를 설치할 경우 새 release object 가 생성되는 것을 알 수 있다.

같은 chart를 여러번 install 할수 있는데 그때마다 새로운 release object 가 생성되어 override 된다.

한번 더 설치해보자.


$ helm install stable/mariadb
NAME:   sullen-ladybird
LAST DEPLOYED: Wed Jan 16 01:34:09 2019
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/Secret
NAME                     TYPE    DATA  AGE
sullen-ladybird-mariadb  Opaque  2     0s

==> v1/ConfigMap
NAME                            DATA  AGE
sullen-ladybird-mariadb-master  1     0s
sullen-ladybird-mariadb-slave   1     0s
sullen-ladybird-mariadb-tests   1     0s

==> v1/Service
NAME                           TYPE       CLUSTER-IP     EXTERNAL-IP  PORT(S)   AGE
sullen-ladybird-mariadb        ClusterIP  10.39.241.50   <none>       3306/TCP  0s
sullen-ladybird-mariadb-slave  ClusterIP  10.39.243.165  <none>       3306/TCP  0s

==> v1beta1/StatefulSet
NAME                            DESIRED  CURRENT  AGE
sullen-ladybird-mariadb-master  1        1        0s
sullen-ladybird-mariadb-slave   1        1        0s

==> v1/Pod(related)
NAME                              READY  STATUS   RESTARTS  AGE
sullen-ladybird-mariadb-master-0  0/1    Pending  0         0s
sullen-ladybird-mariadb-slave-0   0/1    Pending  0         0s


처음 설치했을때 release 이름이 jaunty-ostrich 이였는데 재설치 했을때 sullen-ladybird 으로 바뀐것을 확인할 수 있다. 

만약 따로 release 이름을 정하고 싶으면 intall 명령어 칠때 --name 플래그를 붙이고 이름을 같이 넣어주면 된다.

ex>
helm install stable/mariadb --name my-maria


my-maria 왠지 맘에든다. my-maria로 다시 install 함.




release의 상태정보를 보고싶으면 

helm status [release 이름] 으로 확인 가능하다.


helm status my-maria



LAST DEPLOYED: Wed Jan 16 01:39:37 2019
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/ConfigMap
NAME                     DATA  AGE
my-maria-mariadb-master  1     2m30s
my-maria-mariadb-slave   1     2m30s
my-maria-mariadb-tests   1     2m30s

==> v1/Service
NAME                    TYPE       CLUSTER-IP    EXTERNAL-IP  PORT(S)   AGE
my-maria-mariadb        ClusterIP  10.39.248.9   <none>       3306/TCP  2m30s
my-maria-mariadb-slave  ClusterIP  10.39.242.13  <none>       3306/TCP  2m30s

==> v1beta1/StatefulSet
NAME                     DESIRED  CURRENT  AGE
my-maria-mariadb-master  1        1        2m30s
my-maria-mariadb-slave   1        1        2m30s

==> v1/Pod(related)
NAME                       READY  STATUS   RESTARTS  AGE
my-maria-mariadb-master-0  1/1    Running  0         2m30s
my-maria-mariadb-slave-0   1/1    Running  0         2m30s

==> v1/Secret
NAME              TYPE    DATA  AGE
my-maria-mariadb  Opaque  2     2m30s
...
...



Chart Customizing


helm 의 큰 장점 중 하나가 chart를 install 하기전에 chart value 값을 변경함으로써 커스터마이징이 가능하다는 점이다.

가령 내가 만든 어플리케이션을 chart로 만들때 각종 설정값, domain 이름, cluster 마다 변동되는 환경변수 등을 chart 안에 의존성을 만들지 않고

chart 설치시 외부에서 변경가능하도록 할수 있는것이다. docker image로 만들어서 가져올땐 일일히 설정을 바꿔줘야 하는 불편함이 있는데 helm의 이 기능으로 한방에 해결!!


chart의 어떤 옵션들이 설정가능한지 살펴보려면  helm inspect values 명령어를 사용한다.


$ helm inspect values stable/mariadb
Fetched stable/mariadb-0.3.0.tgz to /Users/mattbutcher/Code/Go/src/k8s.io/helm/mariadb-0.3.0.tgz
## Bitnami MariaDB image version
## ref: https://hub.docker.com/r/bitnami/mariadb/tags/
##
## Default: none
imageTag: 10.1.14-r3

## Specify a imagePullPolicy
## Default to 'Always' if imageTag is 'latest', else set to 'IfNotPresent'
## ref: http://kubernetes.io/docs/user-guide/images/#pre-pulling-images
##
# imagePullPolicy:

## Specify password for root user
## ref: https://github.com/bitnami/bitnami-docker-mariadb/blob/master/README.md#setting-the-root-password-on-first-run
##
# mariadbRootPassword:

## Create a database user
## ref: https://github.com/bitnami/bitnami-docker-mariadb/blob/master/README.md#creating-a-database-user-on-first-run
##
# mariadbUser:
# mariadbPassword:

## Create a database
## ref: https://github.com/bitnami/bitnami-docker-mariadb/blob/master/README.md#creating-a-database-on-first-run
##
# mariadbDatabase:
...
...

옵션들을 확인했으면 yaml 파일로 해당 설정들을 override 할 수 있다.

$ echo '{mariadbUser: user0, mariadbDatabase: user0db}' > config.yaml
$ helm install -f config.yaml stable/mariadb

위 명령어는 user0 이라는 mariadb 유저를 만들고 user0db라는 database를 만들어서 user0 유저에게 권한을 부여한다.

yaml 파일을 만들지 않고 install 명령어에 --set name=value 플래그를 추가하는 방식으로도 chart 커스터마이징이 가능하다.

--set 플래그 사용할때와 yaml 파일을 사용할때 문법적 차이가 조금 있는데 자세한 내용은 Helm Doc-Using Helm 을 참고하자.



Upgrade & Rollback


chart의 새버젼이 나오거나 이미 release한 chart의 설정값을 변경하고 싶을때는 helm upgrade 명령어로 수행 가능하다.

계속 test log를 첨부하고 싶은데 테스트 하면서 글을 작성하다보니 qwiklabs 사용시간이 끝나서 지금까지 작업분량이 다 날아가버렸다.

다시 처음부터 구축하긴 귀찮으니 이부분은 공식 Helm Doc에 인용된 테스트 로그로 대신한다.

helm upgrade 사용 예시는 다음과 같다.


$ helm upgrade -f panda.yaml happy-panda stable/mariadb
Fetched stable/mariadb-0.3.0.tgz to /Users/mattbutcher/Code/Go/src/k8s.io/helm/mariadb-0.3.0.tgz
happy-panda has been upgraded. Happy Helming!
Last Deployed: Wed Sep 28 12:47:54 2016
Namespace: default
Status: DEPLOYED
...


위의 명령어는 happy-panda release를 panda.yaml 파일 내용과 함께 동일한 chart로 upgrade 하는 명령어다.

panda.yaml 내용을

mariadbUser: user1

이라고 가정하면 helm get values 명령어를 통해 해당 설정이 잘 반영되었는지 확인 할 수 있다.

$ helm get values happy-panda
mariadbUser: user1


만약 release 가 잘못되었다면 helm rollback [RELEASE] [REVISION] 명령어를 통해 rollback 가능하다.

ex>
$ helm rollback happy-panda 1





지금까지 대략적인 Helm 의 개념과 사용법을 알아보았다.

직접 chart를 생성하는 방법과 이글에서 소개한 내용 외에 다양한 활용법이 있으니 관심있는분은 Helm Docs를 참고하길 바란다. 

Helm과 더불어서 Ksonnet도 쿠버네티스 리소스 배포 관리툴로 많이 쓰이는데 몇일전에 조대협님 블로그에 자세한 소개글이 올라왔으니 참고하면 좋다.



댓글