首页 > 解决方案 > 存储 REST API 返回远程名称经常无法解析

问题描述

我正在调用存储 REST API 来获取容器名称

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

即使存储帐户存在且可访问,此命令也经常返回“无法解析远程名称错误”。只需再次运行该命令即可得到正确的结果。

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

标签: azureazure-storageazure-rest-api

解决方案


根据您提供的信息,您使用客户端凭据流获取访问令牌,然后使用该令牌调用Storage Rest API - List Containers.

你可以使用下面的脚本,它对我有用。

确保您使用的服务主体具有 RBAC 角色,例如Contributor/Owner在您的存储帐户 ->Access Control中,如果没有,请单击Add添加它。

在此处输入图像描述

$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

在此处输入图像描述


推荐阅读