You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用K8s Python API创建Istio Virtual Service报404如何解决?

问题原因

两个核心问题导致创建失败返回404:

  • 接口调用方法选错:DestinationRule、VirtualService这类Istio默认资源属于命名空间级别的自定义资源,不是集群范围资源。create_cluster_custom_object方法对应的API路径是集群级资源的创建路径,对命名空间级资源发起POST请求时路径不存在,因此返回404。你之前调用list_cluster_custom_object能成功,是因为该接口对应路径支持查询全集群所有命名空间下的对应资源,不代表资源是集群级的。
  • 传参变量错误:你读取yaml文件反序列化后的配置存在deployment_template变量中,但调用创建接口时传入的是未定义的body变量,即便接口路径正确也会触发参数错误。
修正步骤
  1. 替换创建接口为命名空间级别的自定义资源创建方法,同时修正传参变量,指定目标命名空间,修正后的代码如下:
import yaml
from kubernetes import client, config

group = 'networking.istio.io' 
version = 'v1alpha3' 
plural = 'destinationrules' 
# 替换为你实际要创建资源的目标命名空间
target_namespace = 'default'

config.load_kube_config()
myclient = client.CustomObjectsApi()

with open('destination-rule.yaml', 'r') as file_reader:
    file_content = file_reader.read()

dr_config = yaml.safe_load(file_content)

api_response = myclient.create_namespaced_custom_object(
    group=group,
    version=version,
    namespace=target_namespace,
    plural=plural,
    body=dr_config
)
print("创建成功,返回结果:", api_response)
  1. (可选优化)调整DestinationRule配置避免路由异常:你当前yaml中spec.host仅写了test,建议补全为Kubernetes服务完整域名,例如同命名空间下的test服务可写为test.default.svc.cluster.local,跨命名空间场景替换对应命名空间名即可。
验证方式

执行代码后,可通过kubectl命令校验资源是否创建成功:

kubectl get destinationrules -n default

返回结果中存在名为test的DestinationRule即为创建成功。后续创建VirtualService时同理,需要调用create_namespaced_custom_object方法,plural参数值为virtualservices。

内容的提问来源于stack exchange,提问作者gkv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 17:27:26