카테고리 없음

kustomization 기초에 대해 알아보자!

미니대왕님 2022. 7. 6. 08:21

1. bases : 
사용자 지정 디렉터리에서 리소스를 추가합니다.

buildMetadata: [managedByLabel, originAnnotations, transformerAnnotations]

Example

File Input

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- service.yaml
buildMetadata: [managedByLabel]

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: myService
spec:
  ports:
  - port: 7002

2. buildMetadata : 
주석 또는 레이블에 빌드에 대한 정보를 포함하기 위한 옵션을 지정합니다.

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- service.yaml
buildMetadata: [managedByLabel]

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: myService
spec:
  ports:
  - port: 7002

kustomize build will produce a resource with an output like the following:

apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/managed-by: kustomize-v4.4.1
  name: myService
spec:
  ports:
  - port: 7002

3. commonAnnotations : 
모든 리소스를 추가하려면 주석을 추가하세요.

Example

File Input

# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

commonAnnotations:
  oncallPager: 800-555-1212

resources:
- deploy.yaml
# deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example
spec:
  ...

4. commonLabels 
모든 리소스를 추가하려면 레이블과 선택기를 추가하세요.

Example

File Input

# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

commonLabels:
  someName: someValue
  owner: alice
  app: bingo

resources:
- deploy.yaml
- service.yaml
# deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: example

5. configMapGenerator:
ConfigMap 리소스를 생성합니다.

# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
configMapGenerator:
- name: my-application-properties
  files:
  - application.properties

# application.properties
FOO=Bar

6. crds: CRD 지원 추가

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

crds:
- crds/typeA.yaml
- crds/typeB.yaml

7. generatorOptions

ConfigMap 및 Secret 생성기 의 동작을 제어 합니다.

 

Example

File Input

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
configMapGenerator:
- name: my-application-properties
  files:
  - application.properties
generatorOptions:
  labels:
    kustomize.generated.resources: config-label
  annotations:
    kustomize.generated.resource: config-annotation
# application.properties
FOO=Bar

Build Output

 

apiVersion: v1
data:
  application.properties: |-
    # application.properties
    FOO=Bar    
kind: ConfigMap
metadata:
  annotations:
    kustomize.generated.resource: config-annotation
  labels:
    kustomize.generated.resources: config-label
  name: my-application-properties-f7mm6mhf59

8. images
이미지의 이름, 태그 및/또는 다이제스트를 수정합니다.

Example

File Input

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
spec:
  template:
    spec:
      containers:
      - name: mypostgresdb
        image: postgres:8
      - name: nginxapp
        image: nginx:1.7.9
      - name: myapp
        image: my-demo-app:latest
      - name: alpine-app
        image: alpine:3.7

# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

images:
- name: postgres
  newName: my-registry/my-postgres
  newTag: v1
- name: nginx
  newTag: 1.8.0
- name: my-demo-app
  newName: my-app
- name: alpine
  digest: sha256:24a0c4b4a4c0eb97a1aabb8e29f18e917d05abfe1b7a7c07857230879ce7d3d3

resources:
- deployment.yaml

Build Output

 

apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
spec:
  template:
    spec:
      containers:
      - image: my-registry/my-postgres:v1
        name: mypostgresdb
      - image: nginx:1.8.0
        name: nginxapp
      - image: my-app:latest
        name: myapp
      - image: alpine@sha256:24a0c4b4a4c0eb97a1aabb8e29f18e917d05abfe1b7a7c07857230879ce7d3d3
        name: alpine-app

9. labels
모든 리소스에 레이블 및 선택적으로 선택기를 추가합니다.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

labels:
  - pairs:
      someName: someValue
      owner: alice
      app: bingo
    includeSelectors: true # <-- false by default

Example

File Input

# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

labels:
  - pairs:
      someName: someValue
      owner: alice
      app: bingo

resources:
- deploy.yaml
- service.yaml
# deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: example

Build Output

 

apiVersion: v1
kind: Service
metadata:
  labels:
    app: bingo
    owner: alice
    someName: someValue
  name: example
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: bingo
    owner: alice
    someName: someValue
  name: example

10. namePrefix
모든 리소스 및 참조의 이름 앞에 값을 추가합니다.

Example

File Input

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
spec:
  replicas: 5
  template:
    containers:
      - name: the-container
        image: registry/container:latest
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namePrefix: custom-prefix-

resources:
- deployment.yaml

Build Output

 

apiVersion: apps/v1
kind: Deployment
metadata:
  name: custom-prefix-the-deployment
spec:
  replicas: 5
  template:
    containers:
    - image: registry/container:latest
      name: the-container

11. namespace
모든 리소스에 네임스페이스를 추가합니다.

Example

File Input

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
  namespace: the-namespace
spec:
  replicas: 5
  template:
    containers:
      - name: the-container
        image: registry/conatiner:latest
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: kustomize-namespace

resources:
- deployment.yaml

Build Output

apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
  namespace: kustomize-namespace
spec:
  replicas: 5
  template:
    containers:
    - image: registry/conatiner:latest
      name: the-container


12. nameSuffix
모든 리소스 및 참조의 이름에 값을 추가합니다.

Example

File Input

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
spec:
  replicas: 5
  template:
    containers:
      - name: the-container
        image: registry/conatiner:latest
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

nameSuffix: -custom-suffix

resources:
- deployment.yaml

Build Output

apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment-custom-suffix
spec:
  replicas: 5
  template:
    containers:
    - image: registry/conatiner:latest
      name: the-container

13. openapi
kustomize가 OpenAPI 스키마를 가져오는 위치를 지정합니다.

resources:
- my_resource.yaml

openapi:
  path: my_schema.json

사용자 지정 파일 의 openapi필드는 위의 예에서와 같이 사용자 지정 스키마 파일의 경로일 수 있습니다. 또한 내장된 kubernetes OpenAPI 스키마를 사용하도록 kustomize에 명시적으로 지시하는 데 사용할 수도 있습니다.

resources:
- my_resource.yaml

openapi:
  version: v1.20.4

명령으로 사용할 수 있는 내장 kubernetes OpenAPI 스키마를 확인할 수 있습니다 kustomize openapi info.

다음은 사용자 지정 OpenAPI 스키마 파일로 편집할 수 있는 사용자 지정 리소스의 예입니다. 다음과 같습니다.

apiVersion: example.com/v1alpha1
kind: MyResource
metadata:
  name: service
spec:
  template:
    spec:
      containers:
      - name: server
        image: server
        command: example
        ports:
        - name: grpc
          protocol: TCP
          containerPort: 8080

이 리소스에는 이미지 필드가 있습니다. 패치로 값을 에서 server  변경해 보겠습니다 . nginx명령을 사용하여 로컬에서 선호하는 클러스터에서 이와 같은 OpenAPI 문서를 얻을 수 있습니다 kustomize openapi fetch. Kustomize는 OpenAPI 확장 x-kubernetes-patch-merge-key을 x-kubernetes-patch-strategy사용하고 전략적 병합을 수행합니다. x-kubernetes-patch-strategy"병합"으로 설정해야 하며 병합 키를 원하는 대로 설정할 수 있습니다.


14. patches
패치 리소스

패치(오버레이라고도 함)는 리소스의 필드를 추가하거나 재정의합니다. patchesKustomization 필드 를 사용하여 제공됩니다 .

patches필드에는 지정된 순서대로 적용할 패치 목록이 포함됩니다 .

각 패치는 다음을 수행할 수 있습니다. group패치 대상은 , version, kind, name, namespace, labelSelector로 리소스를 선택합니다 annotationSelector. 지정된 모든 필드와 일치하는 모든 리소스 에는 패치가 적용됩니다(정규 표현식).

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

patches:
- path: patch.yaml
  target:
    group: apps
    version: v1
    kind: Deployment
    name: deploy.*
    labelSelector: "env=dev"
    annotationSelector: "zone=west"
- patch: |-
    - op: replace
      path: /some/existing/path
      value: new value    
  target:
    kind: MyKind
    labelSelector: "env=dev"

패치 대상 선택기 의 name및 namespace필드는 자동으로 고정된 정규식입니다. 

이는 값 myapp 이 와 동일 함을 의미합니다 ^myapp$.

패치를 사용하면 allowNameChange 및 allowKindChange 옵션을 사용하여 편집 중인 리소스의 종류나

이름을 재정의할 수 있습니다. 

예를 들어:

resources:
- deployment.yaml
patches:
- path: patch.yaml
  target:
    kind: Deployment
  options:
    allowNameChange: true
    allowKindChange: true

기본적으로 이 필드는 false이며 패치는 리소스의 종류와 이름을 그대로 유지합니다.


15. patchesJson6902
json 6902 표준 을 사용하여 리소스 패치

이 목록의 각 항목은 kubernetes 객체와 해당 객체에 적용될 JSON 패치로 해석되어야 합니다. JSON 패치는 https://tools.ietf.org/html/rfc6902 에 설명되어 있습니다.

대상 필드는 개체의 그룹, 버전, 종류, 이름 및 네임스페이스별로 동일한 사용자 지정 내에서 kubernetes 개체를 가리킵니다. 경로 필드는 JSON 패치 파일의 상대 파일 경로입니다. 이 패치 파일의 내용은 다음과 같은 JSON 형식일 수 있습니다.

 [
   {"op": "add", "path": "/some/new/path", "value": "value"},
   {"op": "replace", "path": "/some/existing/path", "value": "new value"},
   {"op": "copy", "from": "/some/existing/path", "path": "/some/path"},
   {"op": "move", "from": "/some/existing/path", "path": "/some/existing/destination/path"},
   {"op": "remove", "path": "/some/existing/path"},
   {"op": "test", "path": "/some/path", "value": "my-node-value"}
 ]

또는 YAML 형식으로

# add: creates a new entry with a given value
- op: add
  path: /some/new/path
  value: value
# replace: replaces the value of the node with the new specified value
- op: replace
  path: /some/existing/path
  value: new value
# copy: copies the value specified in from to the destination path
- op: copy
  from: /some/existing/path
  path: /some/path
# move: moves the node specified in from to the destination path
- op: move
  from: /some/existing/path
  path: /some/existing/destination/path
# remove: delete's the node('s subtree)
- op: remove
  path: /some/path
# test: check if the specified node has the specified value, if the value differs it will throw an error
- op: test
  path: /some/path
  value: "my-node-value"
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

patchesJson6902:
- target:
    version: v1
    kind: Deployment
    name: my-deployment
  path: add_init_container.yaml
- target:
    version: v1
    kind: Service
    name: my-service
  path: add_service_annotation.yaml

패치 내용도 인라인 문자열이 될 수 있습니다.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

patchesJson6902:
- target:
    version: v1
    kind: Deployment
    name: my-deployment
  patch: |-
    - op: add
      path: /some/new/path
      value: value
    - op: replace
      path: /some/existing/path
      value: "new value"    

16.patchesStrategicMerge
전략적 병합 패치 표준을 사용하여 리소스를 패치합니다.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

patchesStrategicMerge:
- service_port_8888.yaml
- deployment_increase_replicas.yaml
- deployment_increase_memory.yaml

패치 내용도 인라인 문자열이 될 수 있습니다.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

patchesStrategicMerge:
- |-
  apiVersion: apps/v1
  kind: Deployment
  metadata:
    name: nginx
  spec:
    template:
      spec:
        containers:
          - name: nginx
            image: nignx:latest  

kustomize는 삭제 지시문 이 포함된 동일한 개체에 대해 둘 이상의 패치를 지원하지 않습니다 . 개체에서 여러 필드/슬라이스 요소를 제거하려면 필요한 모든 삭제를 수행하는 단일 패치를 만듭니다.

패치는 이전 이름이나 종류로 리소스를 참조할 수 있습니다. 예를 들어 리소스가 이름 접두사 변환을 거친 경우 현재 이름, 원래 이름 또는 중간 이름으로 리소스를 참조할 수 있습니다.


17. replacements
N 대상의 필드를 소스의 필드로 대체하십시오.
replacements필드는 대체 경로를 지원할 수 있습니다 .

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

replacements:
  - path: replacement.yaml

replacement.yaml

source:
  kind: Deployment
  fieldPath: metadata.name
targets:
  - select:
      name: my-resource


또는 replacements인라인 교체를 지원합니다.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

replacements:
- source:
    kind: Deployment
    fieldPath: metadata.name
  targets:
  - select:
      name: my-resource

18. replacements
리소스의 복제본 수를 변경합니다.
이 kubernetes 배포 조각이 주어지면:

kind: Deployment
metadata:
  name: deployment-name
spec:
  replicas: 3

사용자 지정에 다음을 추가하여 복제본 수를 5로 변경할 수 있습니다.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

replicas:
- name: deployment-name
  count: 5

이 필드는 목록을 허용하므로 동시에 많은 리소스를 수정할 수 있습니다.

이 선언은 다음 중 하나에 해당하는 이름과 일치하는 항목을 입력하지 않으며 일치 kind:하지도 않습니다 .group:groupkind

  • Deployment
  • ReplicationController
  • ReplicaSet
  • StatefulSet

더 복잡한 사용 사례의 경우 패치 사용으로 되돌리십시오.

예시

입력 파일

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
spec:
  replicas: 5
  template:
    containers:
      - name: the-container
        image: registry/conatiner:latest
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

replicas:
- name: the-deployment
  count: 10

resources:
- deployment.yaml

19. resources
포함할 리소스.

이 목록의 각 항목은 파일 에 대한 경로이거나 다른 kustomization 디렉토리  참조하는 경로(또는 URL)여야 합니다 .

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
- myNamespace.yaml
- sub-dir/some-deployment.yaml
- ../../commonbase
- github.com/kubernetes-sigs/kustomize/examples/multibases?ref=v1.0.6
- deployment.yaml
- github.com/kubernets-sigs/kustomize/examples/helloWorld?ref=test-branch

리소스는 깊이 우선 순위로 읽고 처리됩니다.

파일에는 YAML 형식의 k8s 리소스가 포함되어야 합니다. 파일에는 문서 마커로 구분된 여러 리소스가 포함될 수 있습니다 ---. 파일 경로는 필드 를 포함하는 사용자 정의 파일을 보유하는 디렉토리에 상대적resources 으로 지정되어야 합니다.

디렉토리 사양은 상대, 절대 또는 URL의 일부일 수 있습니다. URL 사양은 hashcorp URL 형식 을 따라야 합니다. 디렉토리는 kustomization.yaml파일을 포함해야 합니다.


20. secretGenerator
비밀 리소스를 생성합니다.

예시

파일 입력

# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
secretGenerator:
- name: app-tls
  files:
    - "tls.crt"
    - "tls.key"
  type: "kubernetes.io/tls"
# tls.crt
LS0tLS1CRUd...tCg==
# tls.key
LS0tLS1CRUd...0tLQo=

빌드 출력

apiVersion: v1
data:
  tls.crt: TFMwdExTMUNSVWQuLi50Q2c9PQ==
  tls.key: TFMwdExTMUNSVWQuLi4wdExRbz0=
kind: Secret
metadata:
  name: app-tls-c888dfbhf8
type: kubernetes.io/tls

21. vars
대체 이름 참조.

vars를 교체로 변환

vars를 더 이상 사용하지 않을 계획이 있으므로 가능한 한 빨리 대체품 으로 마이그레이션하는 것이 좋습니다.

단순 마이그레이션 예

먼저 이 변환을 수동으로 수행하는 방법에 대한 간단한 예를 들어 보겠습니다. 비밀을 참조하는 컨테이너가 있다고 가정합니다(위의 예와 유사).

pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - image: myimage
    name: hello
    env:
    - name: SECRET_TOKEN
      value: $(SOME_SECRET_NAME)

그리고 우리는 다음과 같이 vars를 사용하고 있습니다:

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
- pod.yaml
- secret.yaml

vars:
- name: SOME_SECRET_NAME
  objref:
    kind: Secret
    name: my-secret
    apiVersion: v1

로 변환 vars하려면 replacements다음을 수행해야 합니다.

  1. $(SOME_SECRET_NAME)의 모든 인스턴스를 임의의 자리 표시자 값으로 바꿉니다.
  2. vars objref필드를 교체 source 필드로 변환합니다.
  3. vars 를 1단계에서 자리 표시자 값의 모든 인스턴스를 가리키는 교체name 필드 로 교체합니다. targets

여기에 있는 간단한 예에서는 다음과 같습니다.

pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - image: myimage
    name: hello
    env:
    - name: SECRET_TOKEN
      value: SOME_PLACEHOLDER_VALUE

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
- pod.yaml
- secret.yaml

replacements:
- source:
    kind: Secret
    name: my-secret
    version: v1
  targets:
  - select: 
      kind: Pod
      name: my-pod
    fieldPaths:
    - spec.containers.[name=hello].env.[name=SECRET_TOKEN].value

더 복잡한 마이그레이션 예

좀 더 복잡한 vars 사용법을 살펴보고 이를 교체 로 변환해 보겠습니다 . wordpress 예제 의 var 를 교체 로 변환할 것 입니다.

wordpress 예제의 디렉토리 구조는 다음과 같습니다.

.
├── README.md
├── kustomization.yaml
├── mysql
│   ├── deployment.yaml
│   ├── kustomization.yaml
│   ├── secret.yaml
│   └── service.yaml
├── patch.yaml
└── wordpress
    ├── deployment.yaml
    ├── kustomization.yaml
    └── service.yaml

어디에 patch.yaml다음과 같은 내용이 있습니다.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: wordpress
spec:
  template:
    spec:
      initContainers:
      - name: init-command
        image: debian
        command: ["/bin/sh"]
        args: ["-c", "echo $(WORDPRESS_SERVICE); echo $(MYSQL_SERVICE)"]
      containers:
      - name: wordpress
        env:
        - name: WORDPRESS_DB_HOST
          value: $(MYSQL_SERVICE)
        - name: WORDPRESS_DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-pass
              key: password

최상위 레벨 kustomization.yaml에는 다음과 같은 내용이 있습니다.

resources:
- wordpress
- mysql
patchesStrategicMerge:
- patch.yaml
namePrefix: demo-

vars:
- name: WORDPRESS_SERVICE
  objref:
    kind: Service
    name: wordpress
    apiVersion: v1
- name: MYSQL_SERVICE
  objref:
    kind: Service
    name: mysql
    apiVersion: v1

이 예에서 패치는 다음 용도로 사용됩니다.

  • mysql 서비스 이름을 표시하는 초기 컨테이너 추가
  • wordpress가 mysql 데이터베이스를 찾을 수 있도록 하는 환경 변수 추가

이 더 복잡한 경우에도 이전 예제와 동일한 단계를 수행하여 vars를 교체로 변환할 수 있습니다. 이렇게 하려면 내용을 다음과 같이 변경할 수 있습니다 patch.yaml.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: wordpress
spec:
  template:
    spec:
      initContainers:
      - name: init-command
        image: debian
        command: ["/bin/sh"]
        args: ["-c", "echo", "WORDPRESS_SERVICE", ";", "echo", "MYSQL_SERVICE"]
      containers:
      - name: wordpress
        env:
        - name: WORDPRESS_DB_HOST
          value: MYSQL_SERVICE
        - name: WORDPRESS_DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-pass
              key: password

그런 다음 사용자 지정에서 다음을 대체할 수 있습니다.

kustomization.yaml

resources:
- wordpress
- mysql
patchesStrategicMerge:
- patch.yaml
namePrefix: demo-

replacements:
- source: 
    name: demo-wordpress
    kind: Service
    version: v1
  targets:
  - select: 
      kind: Deployment
      name: demo-wordpress
    fieldPaths:
    - spec.template.spec.initContainers.[name=init-command].args.2
- source: 
    name: demo-mysql
    kind: Service
    version: v1
  targets:
  - select: 
      kind: Deployment
      name: demo-wordpress
    fieldPaths:
    - spec.template.spec.initContainers.[name=init-command].args.5
    - spec.template.spec.containers.[name=wordpress].env.[name=WORDPRESS_DB_HOST].value