Helm - Adfinis SyGroup...What is Helm? Helm is a tool for managing Kubernetes charts. Charts are...

Preview:

Citation preview

Helm

Besmart.Thinkopensource.

WhatisHelm?HelmisatoolformanagingKubernetescharts.

Chartsarepackagesofpre-configuredresources.

Thinkofitlikeapt/yum/homebrewforKubernetes.

WhyHelm?

De-factostandardfortemplatingk8sconfigsOfficialKubernetesprojectmaintainedbyCNCFRepeatableapplicationinstallationsPainlessupdatesShipswithreadytousechartsmadebythecommunitybestpracticesarebakedintoofficalcharts

What'swrongwithkubectl?

ResourcesneedtobemutatedafteradeployYoucan kubectledit<resource>

But,needtoimplementyourownupdatingandrollbackordependonvendorspecifictoolingforlifecyclemanagement

Helmhelpswithlifecyclemanagmentwhileallowingyoutodefineyourinfrastructureascode

HelmBasics

Architecture

helmclienttillerserver-sidecomponent

Demo:Quickstart#deploytillertokube-systemnamespacehelminit#usethe`-c`flagifyourclusteradminhasalreadydeployed#andconfiguredtillerforyou,thisprepares~/.helmhelminit-c#Deployapostgresqlinstancehelminstallstable/postgresql

Inspectinghelmmanagedresources#Showdeployshelmlist#Getinformationonareleasehelmstatusmy-release

HelmreleasesDifferentiatemultipledeploysofachartwithreleases.

Possiblevaluescouldbe.

production , stage , integration

<customer>-production

<app>-postgresql

Thisdependsonyourorganizationsstructureandwhatyouusetheclusterfor.

Whatdidwejustdeploy?

Deploymentbasedon postgres imageNetworkPolicyallowingaccess.PersistentVolumeClaimforstoringdataSecretcontainingautogeneratedpostgres-password

Servicetoexposedatabaseincluster

Addingmetricshelmupgrademy-releasestable/postgresql\--set'metrics.enabled=true'

Wejustdeployedapostgres_exportersidecarcontainerexposingmetricsforPrometheus!

Rollback#simulaterollbackhelmrollback--dry-runmy-releaseold-version#actualrollbackhelmrollbackmy-releaseold-version

Writinghelmcharts

IntializeemptyCharthelmcreatemy-app

my-app/├──charts├──Chart.yaml├──templates│├──deployment.yaml│├──_helpers.tpl│├──ingress.yaml│├──NOTES.txt│└──service.yaml└──values.yaml

TemplatingTheHelmtemplatelanguageisimplementedinthestronglytypedGolanguage.

EachHelmchartcontainsatemplatesdirectorythatcontainsrelevanttemplates.

NamingTemplates

Use .yaml or .tpl suffixforfilesDasherizefilenamesReflectresourcekindinnames

NamingExamples

Good Badfoo-pod.yaml foo-pod.yml

my-example-podtemplates.yaml MyExamplePodTemplates.yaml

my-example-svc.yaml my-example.yaml

Built-inObjects

Everythingbelow Release

Chart variablewithinfosfrom Chart.yaml

Values withdatafrom values.yaml ,thecliandothersources

AcompletelistisintheHelmdocs

ReleaseandChartVariables#Currentrelease{{.Release.Revision}}#Chartinfos{{.Chart.version}}

ValuesThebuilt-inobjectValuesisemptybydefault.Chartsanduserscanaddtoitthrough values.yaml ,user-suppliedfilesandontheCLI.

Let'sseehowvaluesgetpopulatedwithasimpletemplate.

echo'{{.Values.hello.world}}'>templates/hello.tpl

Defaultvaluesareinthecharts values.yaml

#values.yamlhello:world:Hello!

helmtemplate.-xtemplates/hello.yaml

---#Source:my-chart/templates/hello.yamlHello!

OverridingvaluesontheCLIhelmtemplate.--executetemplates/hello.yaml\--set'hello.world=Hallo!'

---#Source:my-chart/templates/hello.yamlHallo!

LocallyoverridingvalueswithaspecificYAMLfile#local.yamlhello:world:Здравствуй!

helmtemplate.--executetemplates/hello.yaml\--valueslocal.yaml

---#Source:my-chart/templates/hello.yamlЗдравствуй!

FunctionsandPipelinesHelmhasover60availablefunctions.SomeofthemarefromGotemplate,somefromSprigtemplatelibrary.

echo'var:{{quote.Values.myvar}}'>templates/quote.yaml

helmtemplate.--executetemplates/quote.yaml\--set'myvar=Thisisastring'

---#Source:my-chart/templates/quote.yamlvar:"Thisisaastring"

FlowControl

if / else forcreatingconditionalblockswith tospecifyascoperange ,whichprovidesa"foreach"-styleloop

if / else

{{-if.Values.ingress.enabled-}}apiVersion:extensions/v1beta1kind:Ingress#...{{-end-}}

range

#...spec:rules:{{-range.Values.server.ingress.hosts}}-host:{{.}}{{-end-}}#...

DebuggingTemplates#verifythatchartfollowsbestpracticeshelmlint#letserverrendertemplatesandreturnresultingmanifesthelminstall--dry-run--debug.#Seewhattemplatesareinstalledontheserverhelmgetmanifestmy-release

NamedTemplates

define declaresanewnamedtemplateinsideofyourtemplateinclude usesanamedtemplateblock declaresaspecialkindoffillabletemplatearea

Templatesareusuallydefinedin templates/_helpers.tpl

The name Template{{/*Expandthenameofthechart.*/}}{{-define"my-chart.name"-}}{{-default.Chart.Name.Values.nameOverride|trunc63|trimSuffix"-"-}}{{-end-}}

The fullname Template{{/*Createadefaultfullyqualifiedappname.Wetruncateat63charsbecausesomeKubernetesnamefieldsarelimitedtothis(bytheDNSnamingspec).*/}}{{-define"my-chart.fullname"-}}{{-$name:=default.Chart.Name.Values.nameOverride-}}{{-printf"%s-%s".Release.Name$name|trunc63|trimSuffix"-"-}}{{-end-}}

The fullname templateisusuallyusedaspartofthein-clusterDNSname.

UsingNamedTemplatesmetadata:name:{{include"my-chart.fullname".}}labels:app:{{include"my-chart.name".}}

metadata:name:my-release-my-chartlabels:app:mychart

HelmHooks

Hookcanbeusedtohookintotheinstall,updateanddeletelifecycleHooksareregulartemplatesTheyarecreatedusingannotationsYoushouldopttoputthemintothe templates/hooks subdirAvailabilitydependsonhelmversion

Hookannotationsmetadata:annotations:"helm.sh/hook":"<hook-type>"

InstallHooks

pre-installpost-install

UpgradeHooks

pre-upgradepost-upgrade

RollbackHooks

pre-rollbackpost-rollback

DeleteHooks

pre-deletepost-delete

CRDHooks

crd-install

UsedonCustomResourceDefinitionstoensurethattheyaredefinedbeforetheyareusedbyothermanifestsinthechart.

TestHooks

test-success

AdditionalAnnotationsmetadata:annotations:"helm.sh/hook-weight":"<num>""helm.sh/hook-delete-policy":"before-hook-creation,hook-succeeded"

Demo:Let'swritesomeinfra

Inthisexamplewewillcreateachartforglances.

Glancescanbescheduledonplaindockerasfollows:

dockerrun\--rm\--detach\--publish61208-61209:61208-61209\--envGLANCES_OPT="-w"\--volume/var/run/docker.sock:/var/run/docker.sock:ro\--pidhost\docker.io/nicolargo/glances

Let'slookatitonlocalhosttoseewhatisdoes.

helmcreateglancescdglances

Forthisexamplewemakesomechangestothedefaultchartgeneratedbyhelm.

values.yamlimage:#pathtodockerhubcontainerrepository:nicolargo/glancesservice:#matchporttoEXPOSEfromimageport:61208

templates/deployment.yamlspec:template:spec:containers:-name:{{.Chart.Name}}#addenvironmenttocontainerenv:-name:GLANCES_OPTvalue:-w

template/NOTES.tpl#changesourceportforport-forwardexampleecho"Visithttp://127.0.0.1:{{.Values.service.internalPort}}touseyourapplication"kubectlport-forward$POD_NAME{{.Values.service.internalPort}}:{{.Values.service.internalPort}}

deploytok8shelminstall.--nameglances-test

BestPractices

UseSemVer2torepresentversionnumber.Indentyamlwith2spaces(andnevertabs).SpecifyatillerVersionSemVercontraintinyouchart.

tillerVersion:">=2.4.0"

uselabelssok8scanidentifyressourcesandtoexposeoperatorsforthepurposeofquerying

Theofficalbestpracticesguidehasmorepointersyoushouldfollow

AdvancedHelming

Composingsystemswithsubcharts

Chartscandependonothercharts.Dependenciesaredescribedin requirements.yaml .helmdepbuild creates requirements.lock .

#downloaddependencieshelmdepbuildstable/redmine

#installredminewithpostgresqlhelminstallstable/redmine\--setdatabaseType.mariadb=false,databaseType.postgresql=true

SubchartsandValues

subchartscannotdependontheirparentchartsvalues.parentchartscanoverridevaluesforsubcharts.globalvaluescanbeaccessedfromanychart.

#overridepostgresqlvaluespostgresql:postgresPassword:muchsecretverysecure

#definesomeglobalvariablesglobal:myVariable:myValue

Pleaseplanaheadwhenusingglobalsordon'tusethematall.Officialchartsrarelyusethem.

UsingyourownStarterYoucansupplyyouownstarterfor helmcreate .

mkdir-p~/.helm/starters/my-starter/templatescd~/.helm/starters/my-startervimtemplates/deployment.yamlcd~/git.repos/helmcreate-pmy-startermy-chart

ManagingvendorspecificresourcesHelmcanbeusedtomanageanyresourcesthatareavailablethroughak8sstyleAPIendpoint.

apiVersion:apps.openshift.io/v1kind:DeploymentConfigmetadata:name:{{.Values.name|quote}}annotations:description:Defineshowtodeploytheapplicationservertemplate.alpha.openshift.io/wait-for-ready:'true'spec:#...

MoreinfosareontheOpenShiftblog.

Thanks

SlidesTheseslidesmaybefoundonad-sy.ch/helm-training.

FeelfreetoContactuswww.adfinis-sygroup.ch

GitHub

info@adfinis-sygroup.ch

Twitter

Recommended