From f21f6be26b443fb83766854c2eb5a7a354aa2e1e Mon Sep 17 00:00:00 2001 From: Judit Novak Date: Thu, 16 Nov 2023 16:46:01 +0100 Subject: [PATCH] Updates safe to switch from secret ID to label --- src/charm.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/charm.py b/src/charm.py index 2ba37ae158..8d8be4457a 100755 --- a/src/charm.py +++ b/src/charm.py @@ -41,6 +41,7 @@ JujuVersion, MaintenanceStatus, Relation, + SecretNotFoundError, Unit, WaitingStatus, ) @@ -211,6 +212,14 @@ def _translate_field_to_secret_key(self, key: str) -> str: new_key = key.replace("_", "-") return new_key.strip("-") + def _safe_get_secret(self, scope: Scopes, label: str) -> SecretCache: + try: + return self.secrets.get(label) + except SecretNotFoundError: + if secret_uri := self._peer_data(scope).get(SECRET_INTERNAL_LABEL): + return self.secrets.get(label, secret_uri) + raise + def get_secret(self, scope: Scopes, key: str) -> Optional[str]: """Get secret from the secret storage.""" if scope not in get_args(Scopes): @@ -220,15 +229,15 @@ def get_secret(self, scope: Scopes, key: str) -> Optional[str]: return value if JujuVersion.from_environ().has_secrets: - secret_key = self._translate_field_to_secret_key(key) label = generate_secret_label(self, scope) for attempt in Retrying(stop=stop_after_attempt(3), wait=wait_fixed(1), reraise=True): with attempt: - secret = self.secrets.get(label) + secret = self._safe_get_secret(scope, label) if not secret: return + secret_key = self._translate_field_to_secret_key(key) value = secret.get_content().get(secret_key) if value != SECRET_DELETED_LABEL: return value @@ -248,7 +257,7 @@ def set_secret(self, scope: Scopes, key: str, value: Optional[str]) -> Optional[ secret_key = self._translate_field_to_secret_key(key) label = generate_secret_label(self, scope) - secret = self.secrets.get(label) + secret = self._safe_get_secret(scope, label) if not secret: self.secrets.add(label, {secret_key: value}, scope) else: @@ -267,7 +276,7 @@ def remove_secret(self, scope: Scopes, key: str) -> None: if JujuVersion.from_environ().has_secrets: secret_key = self._translate_field_to_secret_key(key) label = generate_secret_label(self, scope) - secret = self.secrets.get(label) + secret = self._safe_get_secret(scope, label) if not secret: return