Как восстановить ключ хранилища Azure для Classic и ARM с помощью REST API - PullRequest
0 голосов
/ 13 декабря 2018

Используя API Azure Rest, можно повторно создать первичный и вторичный ключи для учетной записи Classic Storage и учетной записи хранения на основе Azure Resource Manager.

1 Ответ

0 голосов
/ 13 декабря 2018

Ниже сценарий использует запрос API REST через приложение Azure Active Directory, чтобы обратиться к ресурсу Azure и выполнить необходимые действия.

Подробнее о настройке Приложение Azure Active Directory

Для выполнения этого сценария необходимо убедиться, что приложение Azure Active Directory имеет разрешение «Участник» наГруппа ресурсов, в которой размещена учетная запись хранения.

    $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
        }
    }
...