From 984a69ceb493479cf7b1962a44d1653f91ad5a40 Mon Sep 17 00:00:00 2001 From: Aleksandr Seleznev Date: Tue, 8 Aug 2023 06:57:33 +0300 Subject: [PATCH] Use patch() API call for manually created Secret which belongs to ServiceAccount --- k8s_handle/k8s/adapters.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/k8s_handle/k8s/adapters.py b/k8s_handle/k8s/adapters.py index fb79ca3..7cd730d 100644 --- a/k8s_handle/k8s/adapters.py +++ b/k8s_handle/k8s/adapters.py @@ -166,6 +166,21 @@ def replace(self, parameters): name=self.name, body=self.body, namespace=self.namespace ) + # Use patch() for Secrets with ServiceAccount's token to preserve data fields (ca.crt, token, namespace), + # "kubernetes.io/service-account.uid" annotation and "kubernetes.io/legacy-token-last-used" label + # populated by serviceaccount-token controller. + # + # See for details: + # https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#manually-create-an-api-token-for-a-serviceaccount + if self.kind in ['secret']: + if ('type' in self.body and self.body['type'] == 'kubernetes.io/service-account-token' and + 'annotations' in self.body['metadata'] and + 'kubernetes.io/service-account.name' in self.body['metadata']['annotations']): + + return getattr(self.api, 'patch_namespaced_{}'.format(self.kind))( + name=self.name, body=self.body, namespace=self.namespace + ) + if hasattr(self.api, "replace_namespaced_{}".format(self.kind)): return getattr(self.api, 'replace_namespaced_{}'.format(self.kind))( name=self.name, body=self.body, namespace=self.namespace)