Share via


使用 PowerShell 輪替儲存體帳戶存取金鑰

此指令碼會建立 Azure 儲存體帳戶,顯示新儲存體帳戶的主要存取金鑰,然後更新 (輪替) 該金鑰。

此範例需要 Azure PowerShell。 執行 Get-Module -ListAvailable Az 以尋找版本。 如果您需要安裝或升級,請參閱安裝 Azure PowerShell 模組

執行 Connect-AzAccount Cmdlet 以連線到 Azure。

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

範例指令碼

# this script will show how to rotate one of the access keys for a storage account

# get list of locations and pick one
Get-AzLocation | select Location

# save the location you want to use  
$location = "eastus"

# create a resource group
$resourceGroup = "rotatekeystestrg"
New-AzResourceGroup -Name $resourceGroup -Location $location 

# create a standard general-purpose storage account 
$storageAccountName = "contosotestkeys"
New-AzStorageAccount -ResourceGroupName $resourceGroup `
  -Name $storageAccountName `
  -Location $location `
  -SkuName Standard_LRS `

# retrieve the first storage account key and display it 
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName).Value[0]

Write-Host "storage account key 1 = " $storageAccountKey

# re-generate the key
New-AzStorageAccountKey -ResourceGroupName $resourceGroup `
    -Name $storageAccountName `
    -KeyName key1

# retrieve it again and display it 
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName).Value[0]
Write-Host "storage account key 1 = " $storageAccountKey

清除部署

執行下列命令來移除資源群組、儲存體帳戶和所有相關資源。

Remove-AzResourceGroup -Name rotatekeystestrg

指令碼說明

此指令碼使用下列命令來建立儲存體帳戶,並擷取及輪替其中一個存取金鑰。 下表中的每個項目都會連結至特定命令的文件。

Command 注意
Get-AzLocation 取得所有位置和每個位置支援的資源提供者。
New-AzResourceGroup 建立 Azure 資源群組。
New-AzStorageAccount 建立儲存體帳戶。
Get-AzStorageAccountKey 取得 Azure 儲存體帳戶的存取金鑰。
New-AzStorageAccountKey 重新產生 Azure 儲存體帳戶的存取金鑰。

下一步

如需有關 Azure PowerShell 模組的詳細資訊,請參閱 Azure PowerShell 文件

Azure Blob 儲存體的 PowerShell 範例中,提供了其他儲存體 PowerShell 指令碼範例。