Search code examples
azureazure-storageazure-rest-api

Storage REST API Returns Remote Name Could Not be Resolve Often


I am calling the storage REST API to get container names using

Invoke-WebRequest -Method GET -Uri $storage_url -Headers $headers

This command often returns 'remote name could not be resolved error', even when the storage account exists and is reachable. Just running the command again gives correct result.

Invoke-WebRequest : The remote name could not be resolved: '<storageAccountName>.blob.core.windows.net'
At line:1 char:1
+ Invoke-WebRequest -Method GET -Uri $storage_url -Headers $headers #In ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Solution

  • From the information you provided, you use the client credential flow to get the access token, then use the token to call the Storage Rest API - List Containers.

    You could use the script below, it works for me.

    Make sure the service principal you used has a RBAC role e.g. Contributor/Owner in your storage account -> Access Control, if not, click the Add to add it.

    enter image description here

    $ClientID       = "xxxxxxx" 
    $ClientSecret   = "xxxxxxx"  
    $tennantid      = "xxxxxxx"
    $storageaccountname = "joystoragev2"
    
    $TokenEndpoint = {https://login.microsoftonline.com/{0}/oauth2/token} -f $tennantid 
    $Resource = "https://storage.azure.com/"
    
    $Body = @{
            'resource'= $Resource
            'client_id' = $ClientID
            'grant_type' = 'client_credentials'
            'client_secret' = $ClientSecret
    }
    
    $params = @{
        ContentType = 'application/x-www-form-urlencoded'
        Headers = @{'accept'='application/json'}
        Body = $Body
        Method = 'Post'
        URI = $TokenEndpoint
    }
    
    $token = Invoke-RestMethod @params
    
    $accesstoken = $token.access_token
    
    $url = {https://{0}.blob.core.windows.net/?comp=list} -f $storageaccountname
    
    $header = @{
        'Authorization' = 'Bearer ' + $accesstoken
        'x-ms-version' = '2019-02-02'
    }
    
    $response = Invoke-WebRequest –Uri $url –Headers $header –Method GET
    
    $response.RawContent
    

    enter image description here