[英]Retrieving list of secrets from azure keyvault in python
I'm trying to retrieve and print a list of secrets from an azure keyvault use the python sdk.我正在尝试使用 python sdk 从 azure keyvault 检索和打印机密列表。
The following returns an paged.SecretItemPaged object:以下返回一个 paged.SecretItemPaged 对象:
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))
eg:例如:
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: SecretItemPaged 页面是一个迭代器对象,这意味着如果需要,您可以直接在 for 循环中使用它:
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.这里没有魔法,它只是 Python 的迭代器协议。 You can also use
next
, and catch the StopIteration
exception, etc.您还可以使用
next
,并捕获StopIteration
异常等。
Looking at the get_secrets
method, the doc tells you what kind if object it conveys :查看
get_secrets
方法, 该文档会告诉您它所传达的对象类型:
And SecretItem
is documented here . 此处记录了
SecretItem
。
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.请注意,所有 SDK 对象都有一个
as_dict
方法,如果您更喜欢将其作为 dict 处理,而不是具有属性的对象。
Do NOT use the current_page
attribute.不要使用
current_page
属性。 The iterator protocol implementation hides for you fetching multiple pages from Azure if you have more secrets than the default JSON can handle it.如果您有比默认 JSON 可以处理的更多的秘密,迭代器协议实现会为您隐藏从 Azure 获取多个页面。 When doing
list(secrets)
, you might fetch 10 pages and do 10 calls to Azure, you don't know, you don't care :).在执行
list(secrets)
,您可能会获取 10 个页面并对 Azure 进行 10 次调用,您不知道,您不在乎 :)。 current_page
is the state of the last page. current_page
是最后一页的状态。 It is NOT the entire list of elements.它不是整个元素列表。
(I work at MS in this SDK team) (我在这个 SDK 团队的 MS 工作)
Edit Dec/2020编辑 2020 年 12 月
The answer is still valid, though the functionnality has moved into the azure-keyvault-secrets package instead.答案仍然有效,尽管功能已转移到azure-keyvault-secrets包中。 Therefore, import are sligtly different, see sample for reading secrets from KeyVault .
因此,导入略有不同,请参阅示例以从 KeyVault 读取机密。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.