我正在尝试使用kustoize重命名我的服务。
我得到以下错误:
Error: couldn't find target core_v1_Service|~X|~P|SERVICE_NAME|~S for json patch
这是我的基本服务文件:
apiVersion: v1
kind: Service
metadata:
labels:
version: IMAGE_TAG
name: SERVICE_NAME
namespace: my-namespace
spec:
ports:
- name: http-service
port: 8080
protocol: TCP
targetPort: http-service
selector:
app.kubernetes.io/name:
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.name
sessionAffinity: None
type: ClusterIP
这是我的kustomization.yaml文件,我在其中定义了补丁Json6902:
patchesJson6902:
#- target:
# group: apps
# version: v1
# kind: Deployment
# name: DEPLOYMENT_NAME
# path: patch_deployment.yaml
- target:
group: core
version: v1
kind: Service
name: SERVICE_NAME
path: patch_service.yaml
我可以替换我的部署名称,但不能替换服务名称。Kuectl版本:1.16+
我的patch_deployment.yaml和patch_service.yaml文件是非常简单的
- op: replace
path: /metadata/name
value: ${SERVICE_NAME}
我在您的场景中发现了一些问题。
首先,在选择器中,您使用的是向下的api,这将抛出错误:
error: error validating "svc.yaml": error validating data: ValidationError(Service.spec.selector.app.kubernetes.io/name): invalid type for io.k8s.api.core.v1.ServiceSpec.selector: got "map", expected "string"; if you choose to ignore these errors
此处的值应为string
。如果您在PVC
中向下api,您可能会遇到类似的情况。您可以在这里找到更多信息。
第二个问题是patchesJson6902
。如果您查看示例表单文档并找到service
示例,则不会有group: core
,如下所示:
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
但是,在您的场景中,您的service
正在使用namespace: my-namespace
,因此它也应该包含在patchesJson6902
中。
有两种解决方案可以使其发挥作用。
选项1
请记住,您的示例SERVICE_NAME
和IMAGE_TAG
将导致错误:
The Service "SERVICE_NAME" is invalid: metadata.name: Invalid value: "SERVICE_NAME": a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic char
acter, and end with an alphanumeric character (e.g. 'my-name', or 'abc-123', regex used for validation is '[a-z]([-a-z0-9]*[a-z0-9])?')
以下YAML:
>cat svc.yaml
apiVersion: v1
kind: Service
metadata:
labels:
version: image-tag
name: SERVICE_NAME
namespace: my-namespace
>cat kustomization.yaml
resources:
- svc.yaml
patchesJson6902:
- path: patch_service.yaml
target:
version: v1
kind: Service
name: SERVICE_NAME
namespace: my-namespace
>cat patch_service.yaml
- op: replace
path: /metadata/name
value: ${SERVICE_NAME}
>kustomize build
apiVersion: v1
kind: Service
metadata:
labels:
version: image-tag
name: ${SERVICE_NAME}
namespace: my-namespace
变量SERVICE_NAME不会在kustomization期间进行评估。之后必须使用sed或手动替换
选项2
它将需要使用sed命令的小脚本。
>cat kustomization.yaml
resources:
- svc.yaml
patchesJson6902:
- path: patch_service.yaml
target:
version: v1
kind: Service
name: SERVICE_NAME
namespace: my-namespace
>cat kustomsed.sh
#!/bin/bash
SERVICE_NAME=testsvc
kustomize build | sed "s/SERVICE_NAME/${SERVICE_NAME}/"
>./kustomsed.sh
apiVersion: v1
kind: Service
metadata:
labels:
version: image-tag
name: testsvc
namespace: my-namespace
这似乎是kubectl kustosize版本的问题。它适用于kustomize构建。