in gitops/env/stage2/configs/mtk-connect/mtk-connect-post-key/configure-key.py [0:0]
def update_secret_value(secret_name, namespace, new_value, key="password"):
"""
Updates the value of a specific key in a Kubernetes Secret.
Returns result flag: True if operation was succesfull.
"""
result = False
print("\nUpdating secret value.")
try:
config.load_incluster_config()
print("Using in-cluster configuration.")
except config.ConfigException:
config.load_kube_config()
print("Using kubeconfig file.")
v1 = client.CoreV1Api()
try:
# Fetch the existing secret
secret = v1.read_namespaced_secret(name=secret_name, namespace=namespace)
# Update the value of the specified key
if secret.data is None:
secret.data = {} # Ensure `data` exists
# Encode the new value to base64
secret.data[key] = base64.b64encode(new_value.encode()).decode()
# Update the secret in Kubernetes
v1.replace_namespaced_secret(name=secret_name, namespace=namespace, body=secret)
print(f"Updated key '{key}' in secret '{secret_name}' with new value.{secret}")
except client.exceptions.ApiException as e:
if e.status == 404:
print(f"Secret '{secret_name}' not found in namespace '{namespace}'.")
else:
raise e
else:
result = True
finally:
return result