0
votes

Using Azure Rest API, can one regenerate Primary and Secondary Key for Classic Storage account and Azure Resource Manager based storage account.

1

1 Answers

0
votes

Below script leverages REST API query via Azure Active Directory App to reach out Azure Resource and perform necessary action.

More details on how to configure Azure Active Directory APP

For the purpose of this script, you would need to ensure the Azure Active Directory APP has Contributor permission on the Resource Group which host storage account.

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