kt1*_*t14 1 python-3.x kubernetes google-kubernetes-engine
我正在尝试为我node-js-deployment
在 GCE 主机 Kubernetes Cluster 中命名的部署之一创建一个新服务
我按照文档来create_namespaced_service
这是服务数据:
{
"kind": "Service",
"apiVersion": "v1",
"metadata": {
"name": "node-js-service"
},
"spec": {
"selector": {
"app": "node-js"
},
"ports": [
{
"protocol": "TCP",
"port": 80,
"targetPort": 8000
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
这是创建服务的 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)
Run Code Online (Sandbox Code Playgroud)
错误:
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}
Run Code Online (Sandbox Code Playgroud)
但是,如果我传递 JSON,则正在创建该服务。不知道我做错了什么。
非常感谢任何帮助,谢谢。
通过阅读您的代码,您似乎错过了将元数据分配给body.metadata
. 而且您错过了该ports
字段V1ServiceSpec
应该是一个列表,但是您使用了一个单一的V1ServicePort
所以没有测试我认为这应该有效:
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
Run Code Online (Sandbox Code Playgroud)
该定义也可以直接从 json / yaml 加载,如官方存储库中的两个示例所示 - 请参阅exec.py create_deployment.py。
您的解决方案可能如下所示:
api_instance = kubernetes.client.CoreV1Api()
namespace = 'default'
manifest = {
"kind": "Service",
"apiVersion": "v1",
"metadata": {
"name": "node-js-service"
},
"spec": {
"selector": {
"app": "node-js"
},
"ports": [
{
"protocol": "TCP",
"port": 80,
"targetPort": 8000
}
]
}
}
try:
api_response = api_instance.create_namespaced_service(namespace, manifest, pretty='true')
pprint(api_response)
except ApiException as e:
print("Exception when calling CoreV1Api->create_namespaced_endpoints: %s\n" % e)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2971 次 |
最近记录: |