如何使用REST API为Classic和ARM重新生成Azure存储密钥

时间:2018-12-13 02:17:59

标签: azure azure-storage

使用Azure Rest API,可以为经典存储帐户和基于Azure资源管理器的存储帐户重新生成主键和辅助键。

1 个答案:

答案 0 :(得分:0)

以下脚本通过Azure Active Directory应用程序利用REST API查询来访问Azure资源并执行必要的操作。

有关如何配置Azure Active Directory APP

的更多详细信息

就此脚本而言,您需要确保Azure Active Directory APP在哪个主机存储帐户的资源组上具有“贡献者”权限。

    $subscriptionid = "Your Azure Subscription ID"
    $resourcegroup = "Azure Resource Group which host the storage account"
    $storageaccountname = "Azure Storage Account name for which keys needs to be re-generation."

### Below query gets the Oauth URI
    $queryUrl = "https://management.azure.com/subscriptions/$subscriptionid/resourceGroups/$resourcegroup/providers/Microsoft.Storage/storageAccounts/$storageaccountname/listKeys?api-version=2018-07-01"
    $response = try{Invoke-RestMethod -Method GET -Uri $queryUrl -Headers @{}} catch{$_.Exception.Response}
    $authHeader = $response.Headers['www-authenticate']
    $endpoint = [regex]::match($authHeader, 'authorization_uri="(.*?)"').Groups[1].Value
    $oauthUri = "$endpoint/oauth2/token"


### Get the access token. For this you would need to Azure Active Directory APP Id and Key. 
    $clientSecret = $aadClientKey ## AAD App Key
    $oath2Uri = $oauthUri
    $body = 'grant_type=client_credentials'
    $body += '&client_id=' + $aadClientId ## AAD App ID
    $body += '&client_secret=' + [Uri]::EscapeDataString($clientSecret)
    $body += '&resource=' + [Uri]::EscapeDataString("https://management.core.windows.net")
    $headers = @{"Accept"="application/json"}
    $response = try { Invoke-RestMethod -Method POST -Uri $oath2Uri -Headers $headers -Body $body } catch { throw; }
    $accessToken = $response.access_token


### Regenerate storage account key for Classic and ARM based storage account. 
    $header = "Bearer " + $accessToken
    $headers = @{ 'Authorization' = $header;'Content-Type'="application/json";}
    $armPutQueryUrl = "https://management.azure.com/subscriptions/$subscriptionid/resourceGroups/$resourcegroup/providers/Microsoft.Storage/storageAccounts/$storageaccountname/regenerateKey?api-version=2018-07-01"
    $classicPutQueryUrl = "https://management.azure.com/subscriptions/$subscriptionid/resourceGroups/$resourcegroup/providers/Microsoft.ClassicStorage/storageAccounts/$storageaccountname/regenerateKey?api-version=2016-11-01"
    $classicGetQueryUrl = "https://management.azure.com/subscriptions/$subscriptionid/resourceGroups/$resourcegroup/providers/Microsoft.ClassicStorage/storageAccounts/$storageaccountname/listKeys?api-version=2016-11-01"
    $armGetQueryUrl = "https://management.azure.com/subscriptions/$subscriptionid/resourceGroups/$resourcegroup/providers/Microsoft.Storage/storageAccounts/$storageaccountname/listKeys?api-version=2018-07-01"
    $useClassApiCall = $false
    try 
    {
        Invoke-RestMethod -Method POST -Uri $armGetQueryUrl -Headers $headers -Body ($body  | ConvertTo-Json) 
    } 
    catch 
    { 
        try
        {
            Invoke-RestMethod -Method POST -Uri $classicGetQueryUrl -Headers $headers -Body ($body  | ConvertTo-Json)
            $useClassApiCall = $true ## This variable controls from now one wheather the storage account supplied is a classic storage account or an ARM based storage account.
         }
         catch
         {
             throw
         }
    }
    if($useClassApiCall)
    {
        try
        {
            $body = @{"KeyType"='Primary'}
            $keyResponse = try { Invoke-RestMethod -Method POST -Uri $classicPutQueryUrl -Headers $headers -Body ($body  | ConvertTo-Json) } catch { throw; }
            $keyResponses.Add($keyResponse.primaryKey) > $nul
            $body = @{"KeyType"='Secondary'}
            $keyResponse = try { Invoke-RestMethod -Method POST -Uri $classicPutQueryUrl -Headers $headers -Body ($body  | ConvertTo-Json) } catch { throw; }
            $keyResponses.Add($keyResponse.secondaryKey) > $null
        }
        catch
        {
            throw
        }
    }
    else
    {
        try
        {
            $body = @{"keyName"='key1'}
            $keyResponse = try { Invoke-RestMethod -Method POST -Uri $armPutQueryUrl -Headers $headers -Body ($body  | ConvertTo-Json) } catch { throw; }
            $keyResponses.Add($keyResponse.keys[0].value) > $nul
            $body = @{"keyName"='key2'}
            $keyResponse = try { Invoke-RestMethod -Method POST -Uri $armPutQueryUrl -Headers $headers -Body ($body  | ConvertTo-Json) } catch { throw; }
            $keyResponses.Add($keyResponse.keys[1].value) > $null
        }
        catch
        {
            throw
        }
    }