I'm trying to retrieve and print a list of secrets from an azure keyvault use the python sdk.
The following returns an paged.SecretItemPaged object:
from azure.keyvault import KeyVaultClient, KeyVaultAuthentication
from azure.common.credentials import ServicePrincipalCredentials
az_client_id = '*****'
az_secret = '*****'
az_tenant = '*****'
credentials = None
def auth_callback(server, resource, scope):
credentials = ServicePrincipalCredentials(
client_id=az_client_id,
secret=az_secret,
tenant=az_tenant,
resource="https://vault.azure.net"
)
token = credentials.token
return token['token_type'], token['access_token']
client = KeyVaultClient(KeyVaultAuthentication(auth_callback))
secrets = client.get_secrets('https://thevault.vault.azure.net/')
print('vault secrets:\n{}'.format(secrets))
e.g:
vault secrets:
<azure.keyvault.models.secret_item_paged.SecretItemPaged object at 0x7fc494c78b38>
I'm not sure how to handle this object. The documentation isn't giving me any hints, unless I've just missed something.
SecretItemPaged page is an iterator object, meaning you can use it inside a for loop directly if you want:
for item in secrets:
print_my_secret(item)
or change it to a list
secrets_as_list = list(secrets)
No magic here, it's just the iterator protocol of Python. You can also use next
, and catch the StopIteration
exception, etc.
Looking at the get_secrets
method, the doc tells you what kind if object it conveys:
And SecretItem
is documented here.
Note that all SDK object have a as_dict
method if you prefer to work on it as a dict, and not an object with attributes.
Do NOT use the current_page
attribute. The iterator protocol implementation hides for you fetching multiple pages from Azure if you have more secrets than the default JSON can handle it. When doing list(secrets)
, you might fetch 10 pages and do 10 calls to Azure, you don't know, you don't care :). current_page
is the state of the last page. It is NOT the entire list of elements.
(I work at MS in this SDK team)
Edit Dec/2020
The answer is still valid, though the functionnality has moved into the azure-keyvault-secrets package instead. Therefore, import are sligtly different, see sample for reading secrets from KeyVault.