pythonazureazure-secrets

Loop Variables and Set Secrets for Azure Keyvault in Python


so I am creating a Python script that will import secrets to Azure. I have 24 keyvault values and secrets but I need a better way to write this and im struggling. Here's what I have so far:

import os
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential

#keyvault name
keyVaultName = os.environ["XXXXXXXX"]

#keyvault URI
KVUri = f"https://{keyVaultName}.vault.azure.net"

#get credentials from already signed in user
credential = DefaultAzureCredential()

#store user credentials and keyvault URI
client = SecretClient(vault_url=KVUri, credential=credential)

#define keyvault secret names and values
secretName1 = input("app-id-example1")
secretValue1 = input("1234")

secretName2 = input("app-id-example2")
secretValue2 = input("5678")

secretName3 = input("app-id-example3")
secretValue3 = input("9101")

secretName4 = input("app-id-example4")
secretValue4 = input("1213")

#set keyvault secret names and values in Azure
client.set_secret(secretName1, secretValue1)
client.set_secret(secretName2, secretValue2)
client.set_secret(secretName3, secretValue3)
client.set_secret(secretName4, secretValue4)

print(" done.")

print(f"Retrieving your secret from {keyVaultName}.")

retrieved_secret = client.get_secret(secretName1, secretName2, secretName3, secretName4)

print(f"Your secret is '{retrieved_secret.value}'.")

print(" done.")

I would like the block texts smaller i don't know how i've looked at dict key value pairs but I'm not sure how that'd work.

Can someone please help.

EDIT: I developed a python script that allows you to create multiple secrets to 1 keyvault - https://github.com/TechyTish/AzurePy/blob/main/create-azure-secrets-README.md


Solution

  • You can try something like this using key value pairs in a dictionary.

    my_dict = {}
    no_of_secrets = 24
    
    for i in range(no_of_secrets):
      secretName = input("app-id-example ")
      secretValue = input("Secret Value ")
      my_dict[secretName] = secretValue
    
    for Key,Value in my_dict.items():
      client.set_secret(Key, Value)