首页 > 解决方案 > kustomize:如何从命令行传递`newTag`

问题描述

我正在使用https://kustomize.io/下面是我的kustomization.yaml文件,

我有多个 docker 映像,并且在部署期间都具有相同tag的 . 我可以手动更改所有tag值,并且可以kubectl apply -k .通过命令提示符运行它。

问题是,我不想手动更改此文件,我想tag在命令中将值作为命令行参数发送kubectl apply -k .。有没有办法做到这一点?谢谢。

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base
images:
- name: foo/bar
  newTag: "36"
- name: zoo/too
  newTag: "36"

标签: kuberneteskustomize

解决方案


我认为使用文件方法是正确的方法和最佳解决方案,即使在使用您的测试场景时也是如此。

通过正确的方式,我的意思是这就是您应该如何使用 kustomize - 将您的环境特定数据保存到单独的目录中。

kustomize 支持将一个人的整个配置存储在版本控制系统中的最佳实践。

  1. kustomize build .您可以使用以下方法更改这些值之前:
kustomize edit set image foo/bar=12.5

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
...
images:
- name: foo/bar
  newName: "12.5"

  1. 使用envsubst方法:
  • deployment.yamlkustomization.yamlbase目录中:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml


apiVersion: apps/v1
kind: Deployment
metadata:
  name: the-deployment
spec:
  selector:
    matchLabels:
      run: my-nginx
  replicas: 1  
  template:
    metadata:
      labels:
        run: my-nginx
    spec:
      containers:
      - name: test
        image: foo/bar:1.2

带有测试覆盖的目录树:

├── base
│   ├── deployment.yaml
│   └── kustomization.yaml
└── overlays
    └── test
        └── kustomization2.yaml

  • kustomization2.yaml使用目录中的变量创建新的overlay/test
cd overlays/test
cat kustomization2.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base
images:
- name: foo/bar
  newTag: "${IMAGE_TAG}"
export IMAGE_TAG="2.2.11" ; envsubst < kustomization2.yaml > kustomization.yaml ; kustomize build .


output:

apiVersion: apps/v1
kind: Deployment
metadata:
...
    spec:
      containers:
      - image: foo/bar:2.2.11
        name: test

之后目录中的文件envsubst


.
├── base
│   ├── deployment.yaml
│   └── kustomization.yaml
└── overlays
    └── test
        ├── kustomization2.yaml
        └── kustomization.yaml
  1. 您始终可以通过管道将结果从kustomize build .intokubectl中即时更改图像:
kustomize build . | kubectl set image -f -  test=nginx3:4 --local -o yaml 

Output:
apiVersion: apps/v1
kind: Deployment
metadata:
...
    spec:
      containers:
      - image: nginx3:4
        name: test

注意

内置解决方案

CLI args 或 env 变量的构建时副作用

由于要构建的额外 >arguments 或 flags 或通过在构建代码中咨询 shell 环境变量 >values 来更改 kustomize 构建配置输出,会挫败该目标。

kustomize 提供了 kustomization 文件编辑命令。像任何 shell >command 一样,它们可以接受环境变量参数。

例如,要将图像上使用的标签设置为匹配环境>变量,请 kustomize edit set image nginx:$MY_NGINX_VERSION 作为在 kustomize 构建之前执行的一些封装工作流的一部分运行


推荐阅读