我有一个Kubernetes部署,它使用ConfigMap和一些经常更新的配置。目前,我必须通过在本地计算机上运行脚本来手动更新此配置,该脚本通过kubectl
更新ConfigMap。
有没有办法使用Kubernetes API以更自动化的方式(来自Kubernetes内部或外部)?
如果你看看here,有几个Kubernetes客户用多种语言。正式支持Python和Go。您可以通过调用客户端来自动执行这些步骤。
如果您了解Python,可以参考下面的sample。
from __future__ import print_statement
import time
import kubernetes.client from kubernetes.client.rest
import ApiException from pprint import pprint
# Configure API key authorization: BearerToken
kubernetes.client.configuration.api_key['authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# kubernetes.client.configuration.api_key_prefix['authorization'] = 'Bearer'
# create an instance of the API class api_instance =
kubernetes.client.CoreV1Api()
name = 'name_example' # str | name of the ConfigMap
namespace = 'namespace_example' # str | object name and auth scope, such as for teams and projects
body = NULL # object |
pretty = 'pretty_example' # str | If 'true', then the output is pretty printed. (optional)
try:
api_response = api_instance.patch_namespaced_config_map(name, namespace, body, pretty=pretty)
pprint(api_response)
except ApiException as e:
print("Exception when calling CoreV1Api->patch_namespaced_config_map: %s\n" % e)
关于在内部和外部使用API,您可以查看wiki。特别是这个thread解释了如何从pod访问API。
KUBE_TOKEN=$(</var/run/secrets/kubernetes.io/serviceaccount/token)
curl -sSk -H "Authorization: Bearer $KUBE_TOKEN" https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/iot2cloud/configmaps
def updateConfigMap(token):
print(token)
token = "Bearer {}".format(token)
headers = {"Content-Type": "application/merge-patch+json", "authorization":token}
r = requests.patch("{}/api/v1/namespaces/default/configmaps/CONFIMAPNAME".format(KUBERNETES_MASTER), verify=False, headers=headers, json=configData)
return r.content
我之前遇到了一些问题,但是当改变了PATCH请求的标题时。我可以更新我的配置文件。但要注意令牌权限(服务帐户)