問題描述
分享使用Python 代碼列舉出全部 Azure App Service 的證書信息。
最關鍵的信息是證書的過期時間,如果即將過期,可以及時發現並更新證書,避免因證書而導致站點不可訪問。
代碼示例:
from azure.identity import ClientSecretCredential
from azure.identity import AzureAuthorityHosts
from azure.mgmt.web import WebSiteManagementClient
# import logging
# logging.basicConfig(level=logging.DEBUG)
# logging.getLogger("azure.core.pipeline.policies.http_logging_policy").setLevel(logging.DEBUG)
client_id=" "
client_secret=" "
tenant_id=""
# sdk ClientSecretCredential 方式認證
credentials = ClientSecretCredential(
client_id=client_id,
client_secret=client_secret,
tenant_id=tenant_id,
authority=AzureAuthorityHosts.AZURE_CHINA
)
webapp_client = WebSiteManagementClient(credentials,subscription_id=" ",base_url="https://management.chinacloudapi.cn", credential_scopes=["https://management.chinacloudapi.cn/.default"])
certificates = webapp_client.certificates.list_by_resource_group(resource_group_name="<your resource group name>")
print("Certificates in resource group :")
for i in certificates:
# print(i.as_dict())
print( i.thumbprint, i.expiration_date,i.name)
執行的結果
代碼解答
這段腳本使用 Azure SDK for Python(azure-identity 與 azure-mgmt-web)在 Azure 中國(21V) 環境下,通過客户端機密方式獲取管理訪問令牌,然後調用 WebSiteManagementClient 列出某個資源組中的 App Service 證書(certificates.list_by_resource_group),並打印每個證書的 指紋(thumbprint)、到期時間(expiration_date) 和 資源名稱(name)。
代碼採用了中國區Azure 管理終結點與 Authority Host,這是在中國雲環境下正確的做法。
逐行解答
# import logging
# logging.basicConfig(level=logging.DEBUG)
# logging.getLogger("azure.core.pipeline.policies.http_logging_policy").setLevel(logging.DEBUG)
這是Python代碼的日誌配置,如果打開,可觀察 SDK 發送的 HTTP 請求/響應流水,非常便於排查權限或終結點問題
開啓日誌後的輸出效果圖:
credentials = ClientSecretCredential(
client_id=client_id,
client_secret=client_secret,
tenant_id=tenant_id,
authority=AzureAuthorityHosts.AZURE_CHINA
)
通過 ClientSecretCredential 獲取令牌,authority=AzureAuthorityHosts.AZURE_CHINA 指定中國區Azure的 AAD 發行者(login.partner.microsoftonline.cn)。沒有這個設置,中國區Azure環境下會因 authority 不匹配導致無法獲取令牌
webapp_client = WebSiteManagementClient(
credentials,
subscription_id="your subscription id",
base_url="https://management.chinacloudapi.cn",
credential_scopes=["https://management.chinacloudapi.cn/.default"]
)
初始化App Service 管理對象 webapp_client。關鍵點:
- subscription_id:目標訂閲。
- base_url:Mooncake 的 **資源管理器(ARM)**終結點(非全球 management.azure.com)。
- credential_scopes:令牌的 資源範圍,在中國雲應請求 https://management.chinacloudapi.cn/.default。這與公共雲的 https://management.azure.com/.default 不同。
certificates = webapp_client.certificates.list_by_resource_group(resource_group_name="<your resource group>")
調用證書管理 API,列出資源組 (需要用真實的值替換 <your resource group>)下的所有 App Service Certificates(包括上傳到 App Service 的私有證書)。
參考資料
[無]
當在複雜的環境中面臨問題,格物之道需:濁而靜之徐清,安以動之徐生。 雲中,恰是如此!