教學課程:使用 Azure Databricks 和 Azure Key Vault 存取 Azure Blob 儲存體

在本教學課程中,您將了解如何使用儲存在 Azure Key Vault 中的秘密,從 Azure Databricks 存取 Azure Blob 儲存體。

在本教學課程中,您會了解如何:

  • 利用 Azure CLI 建立儲存體帳戶和 Blob 容器
  • 建立 Key Vault 並設定祕密
  • 建立 Azure Databricks 工作區並新增 Key Vault 秘密範圍
  • 從 Azure Databricks 工作區存取您的 Blob 容器

必要條件

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

開始本教學課程之前,請先安裝 Azure CLI

利用 Azure CLI 建立儲存體帳戶和 Blob 容器

您必須先建立一般用途的儲存體帳戶,才能使用 blob。 如果您沒有資源群組,請在執行命令之前建立一個。 下列命令會建立並顯示儲存體容器的中繼資料。 複製識別碼

az storage account create --name contosoblobstorage5 --resource-group contosoResourceGroup --location eastus --sku Standard_ZRS --encryption-services blob

Console output of the above command. ID is highlighted in green for end-user to see.

您必須先將儲存體 Blob 資料參與者 角色指派給自己,才可以建立容器來上傳 blob。 在此範例中,系統會將角色指派給您先前建立的儲存體帳戶。

az role assignment create --role "Storage Blob Data Contributor" --assignee t-trtr@microsoft.com --scope "/subscriptions/{subscription-id}/resourceGroups/contosoResourceGroup5/providers/Microsoft.Storage/storageAccounts/contosoblobstorage5

既然您已將角色指派給儲存體帳戶,就可以為您的 blob 建立容器。

az storage container create --account-name contosoblobstorage5 --name contosocontainer5 --auth-mode login

一旦建立了容器,您就可以將 blob (您選擇的檔案) 上傳至該容器。 在此範例中,會上傳含 helloworld 的 .txt 檔案。

az storage blob upload --account-name contosoblobstorage5 --container-name contosocontainer5 --name helloworld --file helloworld.txt --auth-mode login

列出容器中的 blob,以驗證容器是否具有這些 blob。

az storage blob list --account-name contosoblobstorage5 --container-name contosocontainer5 --output table --auth-mode login

Console output of the above command. It displays the file that was just stored in the container.

使用下列命令,取得儲存體容器的 key1 值。 複製此值。

az storage account keys list -g contosoResourceGroup5 -n contosoblobstorage5

Console output of the above command. The value of key1 is highlighted in a green box.

建立 Key Vault 並設定祕密

您將使用下列命令來建立 Key Vault。 此命令也會顯示 Key Vault 的中繼資料。 複製識別碼vaultUri

az keyvault create --name contosoKeyVault10 --resource-group contosoResourceGroup5 --location eastus

ImageConsole output of the above command. The ID and the vaultUri are both highlighted in green for the user to see.

若要建立祕密,請使用下列命令。 將祕密的值設定為您儲存體帳戶中的 key1 值。

az keyvault secret set --vault-name contosoKeyVault10 --name storageKey --value "value of your key1"

建立 Azure Databricks 工作區並新增 Key Vault 秘密範圍

此區段無法透過命令列完成。 您必須存取 Azure 入口網站,才能執行下列動作:

  1. 建立您的 Azure Databricks 資源
  2. 啟動您的工作區
  3. 建立 Azure Key Vault 支援的秘密範圍

從 Azure Databricks 工作區存取您的 Blob 容器

此區段無法透過命令列完成。 您必須使用 Azure Databricks 工作區,才能執行下列動作:

  1. 建立新叢集
  2. 建立新的 Notebook
  3. 填寫 Python 指令碼中的對應欄位
  4. 執行 Python 指令碼
dbutils.fs.mount(
source = "wasbs://<your-container-name>@<your-storage-account-name>.blob.core.windows.net",
mount_point = "/mnt/<mount-name>",
extra_configs = {"<conf-key>":dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")})

df = spark.read.text("/mnt/<mount-name>/<file-name>")

df.show()

下一步

確定您的 Key Vault 可以復原: