Sign in

Filter Out Unused Secrets in Azure Key Vault

There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

This task identifies secrets that have not been accessed or updated for a threshold period, such as 30 or 60 days. It is essential for maintaining optimal security and organization and can be automated using Azure Monitor logs to track secret usage.

from azure.identity import DefaultAzureCredential from azure.keyvault.secrets import SecretClient from azure.core.exceptions import HttpResponseError from azure.monitor.query import LogsQueryClient from datetime import datetime, timedelta, timezone # Azure Key Vault and Monitor configurations #keyVaultName = "vault-eastus-1" # Replace with your Key Vault name key_vault_url = f"https://{key_vault_name}.vault.azure.net" #workspace_id = "c1e806d8-344a-40c0-9632-3ae4da0067c1" # Replace with your Log Analytics Workspace ID # Threshold in days to consider a secret as unused #threshold_days = 30 # Example threshold # Initialize Azure credentials credential = DefaultAzureCredential() # Initialize SecretClient and LogsQueryClient secret_client = SecretClient(vault_url=key_vault_url, credential=credential) logs_query_client = LogsQueryClient(credential) def get_last_accessed_time(secret_name, start_time, end_time): """ Retrieve the last accessed time of a specific secret from Azure Monitor logs. """ query = f""" AzureDiagnostics | where ResourceId == '{key_vault_url}' | where OperationName == 'GetSecret' | extend ParsedSecretName = tostring(split(id_s, '/')[4]) | where ParsedSecretName == '{secret_name}' | top 1 by TimeGenerated desc | project TimeGenerated """ response = logs_query_client.query_workspace(workspace_id, query, timespan=(start_time, end_time)) if response.tables and response.tables[0].rows: return response.tables[0].rows[0][0] return None try: secret_properties = secrets unused_secrets = [] unused_secrets_names = [] secrets_found = False # Determine the start and end times for queries end_time = datetime.now(timezone.utc) start_time = end_time - timedelta(days=threshold_days) for secret in secret_properties: secrets_found = True last_accessed = get_last_accessed_time(secret.name, start_time, end_time) if not last_accessed or (datetime.now(timezone.utc) - last_accessed > timedelta(days=threshold_days)): unused_secrets.append(secret) if not secrets_found: print("No secrets found in the Key Vault.") elif not unused_secrets: print("No unused secrets found.") else: print("Unused secrets:") for secret_name in unused_secrets: print(f"{secret_name.name}\n{'-' * 40}") unused_secrets_names.append(secret_name.name) except HttpResponseError as e: print(f"An error occurred with the Azure HTTP response: {e}") except Exception as e: print(f"An unexpected error occurred: {e}")
copied