我使用一个Kubernetes应用程序和一个只有一个端点的服务。如果使用curl
,我检索它,我得到这样的东西:
{
"kind": "Endpoints",
"apiVersion": "v1",
"metadata": {
...
"subsets": [
{
"addresses": [
{
"ip": "172.16.235.204"
}
],
...
}
]
现在在给定的情况下,我的应用程序需要使用curl PATCH更改其IP。我使用以下代码:
KUBE_SERVICE_DIR="/var/run/secrets/kubernetes.io/serviceaccount"
KUBE_TOKEN_FILENAME="${KUBE_SERVICE_DIR}/token"
KUBE_CA_CERT="${KUBE_SERVICE_DIR}/ca.crt"
KUBE_TOKEN=$(cat ${KUBE_TOKEN_FILENAME})
BODY='[{"op": "replace", "path": "subsets/0/addresses/0/ip", "value": "172.16.140.18"}]'
curl -XPATCH --cacert ${KUBE_CA_CERT} -H "Content-Type: application/json-patch+json" -H "Authorization: Bearer ${KUBE_TOKEN}" --data "${BODY}" "https://${KUBERNETES_API_HOST}:${KUBERNETES_API_PORT}/api/v1/namespaces/cf-db/endpoints/cfdb-ccdb"
正如你所看到的,我的补丁JSON正试图在此路径subsets/0/addresses/0/ip
设置新IP上应用替换操作。但是当我运行它时,我得到:
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {
},
"status": "Failure",
"message": "the server rejected our request due to an error in our request",
"reason": "Invalid",
"details": {
},
"code": 422
有人能帮我找出我的代码有什么问题吗?我尝试了很多变化,也使用StackOverflow的例子,但没有运气。
经过多次尝试和错误,我找到了下面的解决方案。
在Patroni中使用了这样的解决方案(但有用Python编写的),其中服务有一个始终引用主节点的端点。发生故障转移或切换时,光顾代码更新服务端点。这样的代码可以在任何时候使用,只要你有一个StatefulSet,并且你总是想让服务引用主节点,即使在故障转移场景中。
KUBE_SERVICE_DIR="/var/run/secrets/kubernetes.io/serviceaccount"
KUBE_TOKEN_FILENAME="${KUBE_SERVICE_DIR}/token"
KUBE_CA_CERT="${KUBE_SERVICE_DIR}/ca.crt"
KUBE_TOKEN=$(cat ${KUBE_TOKEN_FILENAME})
KUBERNETES_API_HOST=${KUBERNETES_SERVICE_HOST}
KUBERNETES_API_PORT=${KUBERNETES_SERVICE_PORT}
generatePatchData()
{
local MASTER_IP=$1
local MASTER_PORT=$2
cat <<EOF
{"subsets": [{"addresses": [{"ip": "$MASTER_IP"}], "ports": [{"name": "postgresql", "port": $MASTER_PORT, "protocol": "TCP"}]}]}
EOF
}
patchEndpointIP() {
local MASTER_IP=$1
local MASTER_PORT=$2
curl -XPATCH --cacert ${KUBE_CA_CERT} -H "Content-Type: application/merge-patch+json" -H "Authorization: Bearer ${KUBE_TOKEN}" "https://${KUBERNETES_API_HOST}:${K
UBERNETES_API_PORT}/api/v1/namespaces/cf-db/endpoints/cfdb-ccdb" --data "$(generatePatchData $MASTER_IP $MASTER_PORT)"
}
getEndpointIP() {
curl -sSk -H "Authorization: Bearer ${KUBE_TOKEN}" "https://${KUBERNETES_API_HOST}:${KUBERNETES_API_PORT}/api/v1/namespaces/cf-db/endpoints/cfdb-ccdb"
}
patchEndpointIP "172.16.140.13" "5431"
getEndpointIP