[英]Connect Django with Azure MS SQL Server DB using managed identity
[英]Azure SQL Server Database connect using Azure Managed Service Identity (MSI)
我想使用帶有MSI(托管服務標識)身份驗證的python Azure Functions訪問Azure SQL 數據庫。
我試圖找出如何將 Azure sql 與 MSI 從用於 python 的 azure 函數連接起來,但我沒有得到任何信息。
有沒有辦法在 Azure Functions 中使用 MSI 訪問 Azure SQL Server 數據庫?
我想訪問 Azure SQL 數據庫,而無需使用 python 的 azure 函數在我的代碼中傳遞憑據。
我從 azure 函數為 python 啟用了身份選項。
如果你只是想在你的 Azure 函數中隱藏你的 Azure SQL 連接字符串,使用 Azure Key Vault 和 MSI 將是這里的最佳實踐:只需將你的 Azure SQL 連接字符串保存為 Azure Key Vault 中的秘密,然后按照本指南做一些您的 Azure 函數上的配置將滿足您的要求:您的憑據永遠不會出現在您的 Azure 函數中。
我創建了一個密鑰保管庫並將我的 SQL 服務器連接字符串作為機密存儲在 Azure 密鑰保管庫中,請注意機密標識符,因為我們稍后將使用它:
轉到您的密鑰保管庫,為您的函數 msi 配置訪問策略以確保您的函數可以訪問機密: 在您的配置后保存它:
這是我的 python 演示代碼,正如你所看到的,我正在從 Azure Web 應用程序讀取“SQLConn”:
import logging
import os
import azure.functions as func
import pyodbc
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
cnxn = pyodbc.connect(os.environ["SQLConn"])
cursor = cnxn.cursor()
cursor.execute("select @@version")
row = cursor.fetchall()
return func.HttpResponse(str(row))
該值應為:
@Microsoft.KeyVault(SecretUri=<secret_uri_with_version which you noted from key valut>)
完成這些步驟后,您的 azure 函數將能夠從密鑰保管庫中獲取 SQL 連接字符串,並且它不會出現在您的函數應用設置中,並且無需更改代碼。
順便說一句,如果您仍然想使用 MSI 來獲取訪問令牌以連接到您的 Azure SQL , 我在這里發布了一個新的演示,這將對您有所幫助。
我剛剛做了一個快速測試。 完整的一步一步在這里: https : //github.com/crgarcia12/azure-function-msi-python
概括:
你需要:
pyodbc.connect
使用Authentication=ActiveDirectoryMsi
。要將 MSI 用戶添加到數據庫,您必須使用 AAD 管理員進行連接,然后運行以下查詢:
CREATE USER "<MSI user display name>" FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER "<MSI user display name>" -- grant permission to read to database
ALTER ROLE db_datawriter ADD MEMBER "<MSI user display name>" -- grant permission to write to database
<MSI user display name>
通常是 Azure 函數名稱。 您還可以在 PowerShell 中使用Get-AzureADObjectByObjectId -ObjectIds
獲取它
這是一個 hello-world 函數的源代碼:
import logging
import azure.functions as func
# Sql driver
import pyodbc
def main(req: func.HttpRequest) -> func.HttpResponse:
try:
logging.info('Python HTTP trigger function processed a request.')
# Connecting to Azure SQl the standard way
server = 'tcp:<servername>.database.windows.net'
database = '<dbname>'
driver = '{ODBC Driver 17 for SQL Server}' # Driver 13 did not work for me
with pyodbc.connect(
"Driver="
+ driver
+ ";Server="
+ server
+ ";PORT=1433;Database="
+ database
+ ";Authentication=ActiveDirectoryMsi", # This is important :)
) as conn:
logging.info("Successful connection to database")
with conn.cursor() as cursor:
#Sample select query
cursor.execute("SELECT Name FROM People;")
peopleNames = ''
row = cursor.fetchone()
while row:
peopleNames += str(row[0]).strip() + " "
row = cursor.fetchone()
return func.HttpResponse(f"Hello {peopleNames}!")
except Exception as e:
return func.HttpResponse(str(e))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.