我正在尝试为GCE hostes Kubernetes Cluster中名为node-js-deployment
的部署之一创建一项新服务
我按照文档进行了create_namespaced_service
这是服务数据:
{
"kind": "Service",
"apiVersion": "v1",
"metadata": {
"name": "node-js-service"
},
"spec": {
"selector": {
"app": "node-js"
},
"ports": [
{
"protocol": "TCP",
"port": 80,
"targetPort": 8000
}
]
}
}
这是创建服务的Python函数
api_instance = kubernetes.client.CoreV1Api()
namespace = 'default'
body = kubernetes.client.V1Service() # V1Serice
# Creating Meta Data
metadata = kubernetes.client.V1ObjectMeta()
metadata.name = "node-js-service"
# Creating spec
spec = kubernetes.client.V1ServiceSpec()
# Creating Port object
ports = kubernetes.client.V1ServicePort()
ports.protocol = 'TCP'
ports.target_port = 8000
ports.port = 80
spec.ports = ports
spec.selector = {"app": "node-js"}
body.spec = spec
try:
api_response = api_instance.create_namespaced_service(namespace, body, pretty=pretty)
pprint(api_response)
except ApiException as e:
print("Exception when calling CoreV1Api->create_namespaced_service: %s\n" % e)
错误:
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Content-Type': 'application/json', 'Date': 'Tue, 21 Feb 2017 03:54:55 GMT', 'Content-Length': '227'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Service in version \"v1\" cannot be handled as a Service: only encoded map or array can be decoded into a struct","reason":"BadRequest","code":400}
但是如果我传递JSON,则会创建服务。不确定我做错了什么。
非常感谢任何帮助,谢谢。
答案 0 :(得分:3)
通过阅读您的代码,您似乎错过了将元数据分配给body.metadata
。你错过了ports
的{{1}}字段应该是一个列表,但你使用了一个V1ServiceSpec
所以没有测试我认为这应该有效:
V1ServicePort
该定义也可以直接从json / yaml加载,如官方回购中的两个示例所示 - 请参阅exec.py create_deployment.py。
您的解决方案可能如下所示:
api_instance = kubernetes.client.CoreV1Api()
namespace = 'default'
body = kubernetes.client.V1Service() # V1Serice
# Creating Meta Data
metadata = kubernetes.client.V1ObjectMeta()
metadata.name = "node-js-service"
body.metadata = metadata
# Creating spec
spec = kubernetes.client.V1ServiceSpec()
# Creating Port object
port = kubernetes.client.V1ServicePort()
port.protocol = 'TCP'
port.target_port = 8000
port.port = 80
spec.ports = [ port ]
spec.selector = {"app": "node-js"}
body.spec = spec