LoginSignup
5
1

More than 3 years have passed since last update.

kustomize による共通 label の対象から Deployment の selector.matchLabels を除外する

Last updated at Posted at 2020-09-04

バージョン

  • kustomize v3.8.2

文脈

kustomize の commonLabels を使うと、管理するリソースに一括で label を付与する事ができて便利。
しかし commonLabels は deployment.spec.selector.matchLabels のようなイミュータブルなフィールドも編集するので、リソース更新時に事故がよく起きる。
なので commonLabels の編集対象から deployment.spec.selector.matchLabels を外したいということはよくあるのだが、commonLabels ではできない。

方法

LabelSelector というビルトインされたプラグインを使う。

まず kustomization.yaml に transformer を追加する。

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml
transformers:
  - label-transformer.yaml 

次に label-transformer.yaml を作る。

apiVersion: builtin
kind: LabelTransformer
metadata:
  name: metadata-labels
labels:
  app.kubernetes.io/component: database
fieldSpecs:
- path: metadata/labels
  create: true
- path: spec/template/metadata/labels
  kind: Deployment
  create: true

ビルドして確かめると、期待通りの結果になっているはず。

$ kustomize build | grep labels -2
kind: Deployment
metadata:
  labels:
    app.kubernetes.io/name: foo
    app.kubernetes.io/component: database
  name: foo
--
  template:
    metadata:
      labels:
        app.kubernetes.io/name: foo
        app.kubernetes.io/component: database
$ kustomize build | grep matchLabels -2
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: foo # 👈 ここに app.kubernetes.io/component: database が正しく存在しない
  template:

おわりに

どうやら kustomization.yaml に書ける便利機能はだいたい builtin plugins として切り出されているらしい。
kustomize の挙動を調整したくなったらこのページを覗くと良さそう。

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1