Sign in

Delete 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 runbook identifies secrets that haven't been accessed within that time frame. This process, crucial for maintaining security, ensures efficient management by removing outdated or unnecessary secrets.

  1. 1

    List All 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 retrieves the names of all secrets stored in a specific Azure Key Vault. This is typically done to facilitating audit and management of stored secrets. It's a key operation for managing and reviewing the security assets within the Key Vault.

    from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential from azure.core.exceptions import AzureError # Key Vault details #keyVaultName = "your-key-vault-name" KVUri = f"https://{keyVaultName}.vault.azure.net" try: # Authenticate using default credentials credential = DefaultAzureCredential() client = SecretClient(vault_url=KVUri, credential=credential) # List all secrets in the specified Key Vault print(f"Listing all secrets in Key Vault: {keyVaultName}") secrets = client.list_properties_of_secrets() secrets_found = False for secret in secrets: print(f"Secret Name: {secret.name}") print("-" * 40) # Separator line secrets_found = True if not secrets_found: print("No secrets found in the Key Vault.") except AzureError as e: print(f"An Azure error occurred: {e}") except Exception as e: print(f"An unexpected error occurred: {e}")
    copied
    1
  2. 2

    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
    2
  3. 3

    Delete Secrets from Azure Key Vault

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

    This task permanently deletes specific secrets from an Azure Key Vault. It is crucial for managing the lifecycle of sensitive data, ensuring that outdated or unnecessary secrets are securely and efficiently discarded.

    from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential from azure.core.exceptions import AzureError, ResourceNotFoundError # Key Vault details #keyVaultName = "vault-eastus-1" # Replace with your Key Vault name KVUri = f"https://{keyVaultName}.vault.azure.net" # List of secrets to delete #secrets_to_delete = ["test-sercet-3", "secret-2","test-secret-1","test-secret-2"] # Replace with the names of the secrets you want to delete secrets_to_delete = unused_secrets_names try: # Authenticate using default credentials credential = DefaultAzureCredential() client = SecretClient(vault_url=KVUri, credential=credential) secrets_found = False print("Deleting specified secrets...") for secret_name in secrets_to_delete: try: # Attempt to delete the secret print(f"Deleting secret: {secret_name}") delete_operation = client.begin_delete_secret(secret_name) delete_operation.wait() # Wait for the deletion to complete print(f"Secret '{secret_name}' deleted successfully.") secrets_found = True except ResourceNotFoundError: print(f"Secret '{secret_name}' not found. Skipping deletion.") except AzureError as e: print(f"Could not delete secret '{secret_name}': {e}") if not secrets_found: print("No secrets found to delete.") except Exception as e: print(f"An error occurred: {e}")
    copied
    3