client-go中ClientSet调用Apply部署Deployment失败求助
问题分析与解决方案
问题原因
报错invalid object type: /, Kind=的核心原因是:直接实例化的DeploymentApplyConfiguration对象缺少APIVersion和Kind元数据。Server-Side Apply要求传入的对象必须明确自身资源类型,而ApplyConfiguration系列结构体不会像原生Deployment结构体那样自动填充这些字段,导致K8s API Server无法识别对象类型。
Create方法能成功是因为原生apps/v1.Deployment结构体默认包含APIVersion: "apps/v1"和Kind: "Deployment"元数据,API Server可直接识别。
解决方案
有两种修复方式:
方式1:使用官方构造函数初始化Apply配置
client-go为每个资源的ApplyConfiguration提供了构造函数,会自动填充正确的APIVersion和Kind:
deploymentApplyConfig := applyappsv1.Deployment(deploymentName, namespace). WithSpec(applyappsv1.DeploymentSpec(). WithReplicas(3). WithSelector(applymetav1.LabelSelector(). WithMatchLabels(map[string]string{"app": "test-app"})). WithTemplate(applycorev1.PodTemplateSpec(). WithLabels(map[string]string{"app": "test-app"}). WithSpec(applycorev1.PodSpec(). WithContainers(applycorev1.Container(). WithName("nginx"). WithImage("nginx:1.14.2"). WithPorts(applycorev1.ContainerPort().WithContainerPort(80))))))
方式2:手动添加元数据
若坚持直接实例化结构体,需手动设置APIVersion和Kind字段:
deploymentApplyConfig := applyappsv1.DeploymentApplyConfiguration{ ObjectMetaApplyConfiguration: &applymetav1.ObjectMetaApplyConfiguration{ Name: &deploymentName, Namespace: &namespace, }, // 必须添加以下两行 APIVersion: pointer.String("apps/v1"), Kind: pointer.String("Deployment"), Spec: &applyappsv1.DeploymentSpecApplyConfiguration{ Replicas: pointer.Int32(3), Selector: &applymetav1.LabelSelectorApplyConfiguration{ MatchLabels: map[string]string{ "app": "test-app", }, }, Template: &applycorev1.PodTemplateSpecApplyConfiguration{ ObjectMetaApplyConfiguration: &applymetav1.ObjectMetaApplyConfiguration{ Labels: map[string]string{ "app": "test-app", }, }, Spec: &applycorev1.PodSpecApplyConfiguration{ Containers: []applycorev1.ContainerApplyConfiguration{ { Name: pointer.String("nginx"), Image: pointer.String("nginx:1.14.2"), Ports: []applycorev1.ContainerPortApplyConfiguration{ { ContainerPort: pointer.Int32(80), }, }, }, }, }, }, }, }
验证修复
修改后重新运行代码,Apply方法即可正常识别Deployment资源类型,完成Server-Side Apply操作。
内容的提问来源于stack exchange,提问作者grooby
相关产品推荐
相关产品推荐

