└── pyappregkeyvault.py /pyappregkeyvault.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | from azure.identity import ClientSecretCredential 3 | from azure.keyvault.secrets import SecretClient 4 | 5 | # Information required to authenticate using a Service Principal 6 | tenant_id = " " 7 | client_id = " " 8 | client_secret = " " 9 | 10 | # Information for the Key Vault 11 | keyVaultName = " " 12 | keyVaultUri = f"https://{keyVaultName}.vault.azure.net" 13 | 14 | # Get the application credentials 15 | app_credentials = ClientSecretCredential(tenant_id, client_id, client_secret) 16 | # Connect to Key Vault using app credentials 17 | client = SecretClient(vault_url=keyVaultUri, credential=app_credentials) 18 | 19 | # Check whether student has created a secret in KV to retrieve 20 | existingSecretCreated = input("\nWould you like to retrieve an existing secret? (Y/N): ") 21 | if existingSecretCreated.strip() in ('Y', 'y'): 22 | # Let's read the secret 23 | existingSecretName = input("What is the name of the existing secret: ") 24 | print(f"Now retrieving existing secret, '{existingSecretName.strip()}' from {keyVaultName}...", end=' '), 25 | try: 26 | existingSecret = client.get_secret(existingSecretName.strip()) 27 | except Exception as readEx: 28 | print("\tERROR\n") 29 | print(f"{readEx}\n\nMoving on to next step ...\n") 30 | else: 31 | print("\tOK!\n") 32 | print(f"The existing secret in {keyVaultName}, called '{existingSecretName}, has a value of '{existingSecret.value}'\n") 33 | 34 | if existingSecretCreated.strip() in ('N', 'n'): 35 | print("Not checking existing secret ...\n") 36 | 37 | # Would you like to create a new secret? 38 | newSecret = input("Would you like to create a new secret? (Y/N): ") 39 | if newSecret.strip() in ('Y', 'y'): 40 | # Let's create it 41 | newSecretName = input("Enter a name for your new secret: ") 42 | newSecretValue = input("Enter a value for your new secret: ") 43 | 44 | # Create the new secret 45 | print(f"Now creating a new secret in {keyVaultName}, called '{newSecretName.strip()}', with value '{newSecretValue}' ...", end=' ') 46 | try: 47 | client.set_secret(newSecretName.strip(), newSecretValue) 48 | except Exception as writeEx: 49 | print("\tERROR\n") 50 | print(f"{writeEx}\n\n") 51 | else: 52 | print("\tOK!\n") 53 | 54 | print ("\nAll done. Goodbye!") --------------------------------------------------------------------------------