Set refresh True for retrieving secret content

For retreiving content of secret using get_content(),
use flag refresh=True to always get the latest revision.

Change-Id: I1ec2b2de5c8607b1593be8e5351ddc2c1444ded7
This commit is contained in:
Hemanth Nakkina 2024-02-22 10:26:29 +05:30
parent fb5e1bcf9f
commit 7907fad1ef
No known key found for this signature in database
GPG Key ID: 2E4970F7B143168E
12 changed files with 50 additions and 42 deletions

View File

@ -175,7 +175,7 @@ class VaultKvRequiresHandler(sunbeam_rhandlers.RelationHandler):
if not unit_credentials: if not unit_credentials:
return {} return {}
secret = self.model.get_secret(id=unit_credentials) secret = self.model.get_secret(id=unit_credentials)
secret_content = secret.get_content() secret_content = secret.get_content(refresh=True)
return { return {
"kv_mountpoint": self.interface.get_mount(vault_kv_relation), "kv_mountpoint": self.interface.get_mount(vault_kv_relation),
"vault_url": self.interface.get_vault_url(vault_kv_relation), "vault_url": self.interface.get_vault_url(vault_kv_relation),
@ -499,7 +499,7 @@ class BarbicanVaultOperatorCharm(BarbicanOperatorCharm):
"""Return nonce stored in secret.""" """Return nonce stored in secret."""
try: try:
secret = self.model.get_secret(label=NONCE_SECRET_LABEL) secret = self.model.get_secret(label=NONCE_SECRET_LABEL)
return secret.get_content()["nonce"] return secret.get_content(refresh=True)["nonce"]
except ops.SecretNotFoundError: except ops.SecretNotFoundError:
return None return None

View File

@ -367,7 +367,7 @@ class CinderCephOperatorCharm(charm.OSBaseOperatorCharmK8S):
rbd_secret_uuid_id = self.peers.get_app_data(self.client_secret_key) rbd_secret_uuid_id = self.peers.get_app_data(self.client_secret_key)
if rbd_secret_uuid_id: if rbd_secret_uuid_id:
secret = self.model.get_secret(id=rbd_secret_uuid_id) secret = self.model.get_secret(id=rbd_secret_uuid_id)
secret_data = secret.get_content() secret_data = secret.get_content(refresh=True)
if secret_data.get("key") != ceph_key: if secret_data.get("key") != ceph_key:
secret_data["key"] = ceph_key secret_data["key"] = ceph_key
secret.set_content(secret_data) secret.set_content(secret_data)
@ -396,7 +396,7 @@ class CinderCephOperatorCharm(charm.OSBaseOperatorCharmK8S):
rbd_secret_uuid_id = self.peers.get_app_data(self.client_secret_key) rbd_secret_uuid_id = self.peers.get_app_data(self.client_secret_key)
if rbd_secret_uuid_id: if rbd_secret_uuid_id:
secret = self.model.get_secret(id=rbd_secret_uuid_id) secret = self.model.get_secret(id=rbd_secret_uuid_id)
secret_data = secret.get_content() secret_data = secret.get_content(refresh=True)
uuid = secret_data["uuid"] uuid = secret_data["uuid"]
return uuid return uuid

View File

@ -158,7 +158,7 @@ class BindRndcProvidesRelationHandler(sunbeam_rhandlers.RelationHandler):
rndc_keys_current = {} rndc_keys_current = {}
for name, value in rndc_keys_secret.items(): for name, value in rndc_keys_secret.items():
secret = self.charm.model.get_secret(id=value["secret"]) secret = self.charm.model.get_secret(id=value["secret"])
key_value = secret.get_content()["secret"] key_value = secret.get_content(refresh=True)["secret"]
name = relation.name + ":" + str(relation.id) + "_" + name name = relation.name + ":" + str(relation.id) + "_" + name
rndc_keys_current[name] = value rndc_keys_current[name] = value
rndc_keys_current[name]["secret"] = key_value rndc_keys_current[name]["secret"] = key_value

View File

@ -263,7 +263,7 @@ class BindRndcRequiresRelationHandler(sunbeam_rhandlers.RelationHandler):
secret = self.charm.model.get_secret( secret = self.charm.model.get_secret(
id=rndc_key["secret"], label=RNDC_SECRET_PREFIX + unit_name id=rndc_key["secret"], label=RNDC_SECRET_PREFIX + unit_name
) )
secret_value = secret.get_content()["secret"] secret_value = secret.get_content(refresh=True)["secret"]
rndc_key["secret"] = secret_value rndc_key["secret"] = secret_value
rndc_key["name"] = self.interface.nonce(self._relation) rndc_key["name"] = self.interface.nonce(self._relation)
@ -477,7 +477,7 @@ class DesignateOperatorCharm(sunbeam_charm.OSBaseOperatorAPICharm):
"""Return nonce stored in secret.""" """Return nonce stored in secret."""
try: try:
secret = self.model.get_secret(label=NONCE_SECRET_LABEL) secret = self.model.get_secret(label=NONCE_SECRET_LABEL)
return secret.get_content()["nonce"] return secret.get_content(refresh=True)["nonce"]
except ops.SecretNotFoundError: except ops.SecretNotFoundError:
return None return None

View File

@ -368,7 +368,9 @@ class HeatOperatorCharm(sunbeam_charm.OSBaseOperatorAPICharm):
secret_id = self.leader_get(self.heat_auth_encryption_key) secret_id = self.leader_get(self.heat_auth_encryption_key)
if secret_id: if secret_id:
key = self.model.get_secret(id=secret_id) key = self.model.get_secret(id=secret_id)
return key.get_content().get(self.heat_auth_encryption_key) return key.get_content(refresh=True).get(
self.heat_auth_encryption_key
)
return None return None

View File

@ -484,7 +484,9 @@ export OS_AUTH_VERSION=3
try: try:
credentials_id = self._retrieve_or_set_secret(username) credentials_id = self._retrieve_or_set_secret(username)
credentials = self.model.get_secret(id=credentials_id) credentials = self.model.get_secret(id=credentials_id)
user_password = credentials.get_content().get("password") user_password = credentials.get_content(refresh=True).get(
"password"
)
except SecretNotFoundError: except SecretNotFoundError:
logger.warning("Secret for {username} not found") logger.warning("Secret for {username} not found")
@ -642,7 +644,7 @@ export OS_AUTH_VERSION=3
fernet_secret_id = self.peers.get_app_data("fernet-secret-id") fernet_secret_id = self.peers.get_app_data("fernet-secret-id")
if fernet_secret_id: if fernet_secret_id:
fernet_secret = self.model.get_secret(id=fernet_secret_id) fernet_secret = self.model.get_secret(id=fernet_secret_id)
keys = fernet_secret.get_content() keys = fernet_secret.get_content(refresh=True)
# Remove the prefix from keys retrieved from juju secrets # Remove the prefix from keys retrieved from juju secrets
# startswith can be replaced with removeprefix for python >= 3.9 # startswith can be replaced with removeprefix for python >= 3.9
@ -668,7 +670,7 @@ export OS_AUTH_VERSION=3
credential_keys_secret = self.model.get_secret( credential_keys_secret = self.model.get_secret(
id=credential_keys_secret_id id=credential_keys_secret_id
) )
keys = credential_keys_secret.get_content() keys = credential_keys_secret.get_content(refresh=True)
# Remove the prefix from keys retrieved from juju secrets # Remove the prefix from keys retrieved from juju secrets
# startswith can be replaced with removeprefix for python >= 3.9 # startswith can be replaced with removeprefix for python >= 3.9
@ -784,7 +786,7 @@ export OS_AUTH_VERSION=3
logger.info(f"Creating service account with username {username}") logger.info(f"Creating service account with username {username}")
self.keystone_manager.create_service_account(username, password) self.keystone_manager.create_service_account(username, password)
olduser = event.secret.get_content().get("username") olduser = event.secret.get_content(refresh=True).get("username")
event.secret.set_content( event.secret.set_content(
{"username": username, "password": password} {"username": username, "password": password}
) )
@ -1192,7 +1194,7 @@ export OS_AUTH_VERSION=3
add_suffix_to_username=True, add_suffix_to_username=True,
) )
credentials = self.model.get_secret(id=service_credentials) credentials = self.model.get_secret(id=service_credentials)
credentials = credentials.get_content() credentials = credentials.get_content(refresh=True)
service_username = credentials.get("username") service_username = credentials.get("username")
service_password = credentials.get("password") service_password = credentials.get("password")
except SecretNotFoundError: except SecretNotFoundError:
@ -1274,7 +1276,9 @@ export OS_AUTH_VERSION=3
try: try:
credentials_id = self._retrieve_or_set_secret(username, scope) credentials_id = self._retrieve_or_set_secret(username, scope)
credentials = self.model.get_secret(id=credentials_id) credentials = self.model.get_secret(id=credentials_id)
user_password = credentials.get_content().get("password") user_password = credentials.get_content(refresh=True).get(
"password"
)
except SecretNotFoundError: except SecretNotFoundError:
logger.warning(f"Secret for {username} not found") logger.warning(f"Secret for {username} not found")
@ -1338,7 +1342,7 @@ export OS_AUTH_VERSION=3
try: try:
credentials_id = self._retrieve_or_set_secret(self.admin_user) credentials_id = self._retrieve_or_set_secret(self.admin_user)
credentials = self.model.get_secret(id=credentials_id) credentials = self.model.get_secret(id=credentials_id)
return credentials.get_content().get("password") return credentials.get_content(refresh=True).get("password")
except SecretNotFoundError: except SecretNotFoundError:
logger.warning("Secret for admin credentials not found") logger.warning("Secret for admin credentials not found")
@ -1369,7 +1373,7 @@ export OS_AUTH_VERSION=3
try: try:
credentials_id = self._retrieve_or_set_secret(self.charm_user) credentials_id = self._retrieve_or_set_secret(self.charm_user)
credentials = self.model.get_secret(id=credentials_id) credentials = self.model.get_secret(id=credentials_id)
return credentials.get_content().get("password") return credentials.get_content(refresh=True).get("password")
except SecretNotFoundError: except SecretNotFoundError:
logger.warning("Secret for charm credentials not found") logger.warning("Secret for charm credentials not found")
@ -1455,7 +1459,7 @@ export OS_AUTH_VERSION=3
# keys on the unit if necessary. # keys on the unit if necessary.
if fernet_secret_id: if fernet_secret_id:
fernet_secret = self.model.get_secret(id=fernet_secret_id) fernet_secret = self.model.get_secret(id=fernet_secret_id)
keys = fernet_secret.get_content() keys = fernet_secret.get_content(refresh=True)
if keys and keys != existing_keys_: if keys and keys != existing_keys_:
logger.info("Updating Fernet juju secret") logger.info("Updating Fernet juju secret")
fernet_secret.set_content(existing_keys_) fernet_secret.set_content(existing_keys_)
@ -1502,7 +1506,7 @@ export OS_AUTH_VERSION=3
credential_keys_secret = self.model.get_secret( credential_keys_secret = self.model.get_secret(
id=credential_keys_secret_id id=credential_keys_secret_id
) )
keys = credential_keys_secret.get_content() keys = credential_keys_secret.get_content(refresh=True)
if keys and keys != existing_keys_: if keys and keys != existing_keys_:
logger.info("Updating Credential keys juju secret") logger.info("Updating Credential keys juju secret")
credential_keys_secret.set_content(existing_keys_) credential_keys_secret.set_content(existing_keys_)
@ -1637,9 +1641,9 @@ export OS_AUTH_VERSION=3
if isinstance(value, str) and value.startswith(SECRET_PREFIX): if isinstance(value, str) and value.startswith(SECRET_PREFIX):
try: try:
credentials = self.model.get_secret(id=value) credentials = self.model.get_secret(id=value)
op["params"][param] = credentials.get_content().get( op["params"][param] = credentials.get_content(
param refresh=True
) ).get(param)
except (ModelError, SecretNotFoundError) as e: except (ModelError, SecretNotFoundError) as e:
logger.debug( logger.debug(
f"Not able to retrieve secret {value}: {str(e)}" f"Not able to retrieve secret {value}: {str(e)}"

View File

@ -253,7 +253,7 @@ class OSExporterOperatorCharm(sunbeam_charm.OSBaseOperatorCharmK8S):
if not secret_id: if not secret_id:
return None return None
secret = self.model.get_secret(id=secret_id) secret = self.model.get_secret(id=secret_id)
return secret.get_content()["auth-url"] return secret.get_content(refresh=True)["auth-url"]
def open_ports(self): def open_ports(self):
"""Register ports in underlying cloud.""" """Register ports in underlying cloud."""
@ -332,7 +332,7 @@ class OSExporterOperatorCharm(sunbeam_charm.OSBaseOperatorCharmK8S):
credentials_id = self.leader_get(label) credentials_id = self.leader_get(label)
if credentials_id: if credentials_id:
secret = self.model.get_secret(id=credentials_id) secret = self.model.get_secret(id=credentials_id)
content = secret.get_content() content = secret.get_content(refresh=True)
if content[key] != value: if content[key] != value:
content[key] = value content[key] = value
secret.set_content(content) secret.set_content(content)

View File

@ -341,7 +341,7 @@ class TempestUserIdentityRelationHandler(sunbeam_rhandlers.RelationHandler):
logger.warning("Failed to get openstack credential for tempest.") logger.warning("Failed to get openstack credential for tempest.")
return None return None
secret = self.model.get_secret(id=credentials_id) secret = self.model.get_secret(id=credentials_id)
return secret.get_content() return secret.get_content(refresh=True)
def _hash_ops(self, ops: list) -> str: def _hash_ops(self, ops: list) -> str:
"""Hash ops request.""" """Hash ops request."""
@ -355,7 +355,7 @@ class TempestUserIdentityRelationHandler(sunbeam_rhandlers.RelationHandler):
# simply return the id # simply return the id
if credentials_id: if credentials_id:
secret = self.model.get_secret(id=credentials_id) secret = self.model.get_secret(id=credentials_id)
content = secret.get_content() content = secret.get_content(refresh=True)
if "password" in content: if "password" in content:
return credentials_id return credentials_id
@ -376,9 +376,9 @@ class TempestUserIdentityRelationHandler(sunbeam_rhandlers.RelationHandler):
# update secret if credential_id exists # update secret if credential_id exists
if credential_id: if credential_id:
secret = self.model.get_secret(id=credential_id) secret = self.model.get_secret(id=credential_id)
content = secret.get_content() content = secret.get_content(refresh=True)
content.update(entries) content.update(entries)
if content != secret.get_content(): if content != secret.get_content(refresh=True):
secret.set_content(content) secret.set_content(content)
return credential_id return credential_id
@ -404,7 +404,7 @@ class TempestUserIdentityRelationHandler(sunbeam_rhandlers.RelationHandler):
"""Set up openstack resource ops.""" """Set up openstack resource ops."""
credential_id = self._ensure_credential() credential_id = self._ensure_credential()
credential_secret = self.model.get_secret(id=credential_id) credential_secret = self.model.get_secret(id=credential_id)
content = credential_secret.get_content() content = credential_secret.get_content(refresh=True)
username = content.get("username") username = content.get("username")
password = content.get("password") password = content.get("password")
setup_ops = [ setup_ops = [
@ -472,7 +472,7 @@ class TempestUserIdentityRelationHandler(sunbeam_rhandlers.RelationHandler):
"""Tear down openstack resource ops.""" """Tear down openstack resource ops."""
credential_id = self._ensure_credential() credential_id = self._ensure_credential()
credential_secret = self.model.get_secret(id=credential_id) credential_secret = self.model.get_secret(id=credential_id)
content = credential_secret.get_content() content = credential_secret.get_content(refresh=True)
username = content.get("username") username = content.get("username")
teardown_ops = [ teardown_ops = [
{ {

View File

@ -62,7 +62,7 @@ LIBAPI = 0
# Increment this PATCH version before using `charmcraft publish-lib` or reset # Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version # to 0 if you are raising the major API version
LIBPATCH = 1 LIBPATCH = 2
import logging import logging
from typing import Optional from typing import Optional
@ -183,7 +183,7 @@ class CephAccessRequires(Object):
secret = self._retrieve_secret() secret = self._retrieve_secret()
if not secret: if not secret:
return {} return {}
return secret.get_content() return secret.get_content(refresh=True)
@property @property
def ready(self) -> bool: def ready(self) -> bool:

View File

@ -97,7 +97,7 @@ LIBAPI = 0
# Increment this PATCH version before using `charmcraft publish-lib` or reset # Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version # to 0 if you are raising the major API version
LIBPATCH = 3 LIBPATCH = 4
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -233,7 +233,7 @@ class IdentityCredentialsRequires(Object):
try: try:
credentials = self.charm.model.get_secret(id=credentials_id) credentials = self.charm.model.get_secret(id=credentials_id)
return credentials.get_content().get("username") return credentials.get_content(refresh=True).get("username")
except SecretNotFoundError: except SecretNotFoundError:
logger.warning(f"Secret {credentials_id} not found") logger.warning(f"Secret {credentials_id} not found")
return None return None
@ -246,7 +246,7 @@ class IdentityCredentialsRequires(Object):
try: try:
credentials = self.charm.model.get_secret(id=credentials_id) credentials = self.charm.model.get_secret(id=credentials_id)
return credentials.get_content().get("password") return credentials.get_content(refresh=True).get("password")
except SecretNotFoundError: except SecretNotFoundError:
logger.warning(f"Secret {credentials_id} not found") logger.warning(f"Secret {credentials_id} not found")
return None return None

View File

@ -100,7 +100,7 @@ LIBAPI = 1
# Increment this PATCH version before using `charmcraft publish-lib` or reset # Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version # to 0 if you are raising the major API version
LIBPATCH = 2 LIBPATCH = 3
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -290,7 +290,7 @@ class IdentityServiceRequires(Object):
try: try:
credentials = self.charm.model.get_secret(id=credentials_id) credentials = self.charm.model.get_secret(id=credentials_id)
return credentials.get_content().get("password") return credentials.get_content(refresh=True).get("password")
except SecretNotFoundError: except SecretNotFoundError:
logger.warning(f"Secret {credentials_id} not found") logger.warning(f"Secret {credentials_id} not found")
return None return None
@ -324,7 +324,7 @@ class IdentityServiceRequires(Object):
try: try:
credentials = self.charm.model.get_secret(id=credentials_id) credentials = self.charm.model.get_secret(id=credentials_id)
return credentials.get_content().get("username") return credentials.get_content(refresh=True).get("username")
except SecretNotFoundError: except SecretNotFoundError:
logger.warning(f"Secret {credentials_id} not found") logger.warning(f"Secret {credentials_id} not found")
return None return None

View File

@ -354,7 +354,7 @@ class DBHandler(RelationHandler):
database_name = self.database_name database_name = self.database_name
database_host = data["endpoints"] database_host = data["endpoints"]
user_secret = self.model.get_secret(id=data["secret-user"]) user_secret = self.model.get_secret(id=data["secret-user"])
secret_data = user_secret.get_content() secret_data = user_secret.get_content(refresh=True)
database_user = secret_data["username"] database_user = secret_data["username"]
database_password = secret_data["password"] database_password = secret_data["password"]
database_type = "mysql+pymysql" database_type = "mysql+pymysql"
@ -925,7 +925,9 @@ class TlsCertificatesHandler(RelationHandler):
id=private_key_secret_id id=private_key_secret_id
) )
self._private_key = ( self._private_key = (
private_key_secret.get_content().get("private-key").encode() private_key_secret.get_content(refresh=True)
.get("private-key")
.encode()
) )
return return
@ -1505,7 +1507,7 @@ class UserIdentityResourceRequiresHandler(RelationHandler):
def _get_credentials(self) -> Tuple[str, str]: def _get_credentials(self) -> Tuple[str, str]:
credentials_id = self._ensure_credentials() credentials_id = self._ensure_credentials()
secret = self.model.get_secret(id=credentials_id) secret = self.model.get_secret(id=credentials_id)
content = secret.get_content() content = secret.get_content(refresh=True)
return content["username"], content["password"] return content["username"], content["password"]
def get_config_credentials(self) -> Optional[Tuple[str, str]]: def get_config_credentials(self) -> Optional[Tuple[str, str]]:
@ -1514,7 +1516,7 @@ class UserIdentityResourceRequiresHandler(RelationHandler):
if not credentials_id: if not credentials_id:
return None return None
secret = self.model.get_secret(id=credentials_id) secret = self.model.get_secret(id=credentials_id)
content = secret.get_content() content = secret.get_content(refresh=True)
return content["username"], content["password"] return content["username"], content["password"]
def _update_config_credentials(self) -> bool: def _update_config_credentials(self) -> bool:
@ -1533,7 +1535,7 @@ class UserIdentityResourceRequiresHandler(RelationHandler):
return True return True
secret = self.model.get_secret(id=credentials_id) secret = self.model.get_secret(id=credentials_id)
old_content = secret.get_content() old_content = secret.get_content(refresh=True)
if old_content != content: if old_content != content:
secret.set_content(content) secret.set_content(content)
return True return True