Reputation: 537
Random generated resource names can be rejected by Azure. Is there any Powershell cmdlet to check those names?
I know there is a Test-AzureName. But it only works with a limited type of resources. Not enough for my use case. (Storage, SQL, DNS, Public IP)
And I know there is this REST-API. But when I call it through Invoke-RestMethod, it returns an error: {"error":{"code":"AuthenticationFailed","message":"Authentication failed. The 'Authorization' header is missing."}}
I'm not very good at Powershell, can someone point me out Azure Powershell cmdlet to do such a task or help me to get the REST-API work?
Thanks!
Upvotes: 0
Views: 8825
Reputation: 111
As mentioned above, most of the providers have an API called checkNameAvailability (https://learn.microsoft.com/en-us/search/?search=checkNameAvailability&scope=REST) that you could use to see of a name is already taken or is globally unique. I've wrapped up some of these in a PowerShell function. See https://secureinfra.blog/2019/11/07/test-azure-resource-name-availability/
Upvotes: 0
Reputation: 1009
The core of the question is how to construct authentication http header for the Invoke-Rest to fulfill Azure requirement. You can do it as follows
More detail you can reference How to authenticate Azure Rest API with Azure Service Principal by Powershell for complete sample code.
Upvotes: 0
Reputation: 2267
The Invoke-RestMethod
with "Check resource name" REST API is good enough for your case. But, you need to do some preparation.
First, You need to create an Active Directory application.
For more information about this, see Create Active Directory application and service principal using portal
the following script will give you proper headers for the REST API.
try{
$subscription = Get-AzureRmSubscription
}
catch{
Login-AzureRmAccount
$subscription = Get-AzureRmSubscription
}
$tenantId = $subscription.TenantId
#these are the client id and key you get from the above steps.
$clientId = "<your client id>"
$key = "<your key>"
$authUrl = "https://login.windows.net/${tenantId}"
$AuthContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]$authUrl
$cred = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential $clientId,$key
$result = $AuthContext.AcquireToken("https://management.core.windows.net/",$cred)
$authHeader = @{
'Content-Type'='application/json'
'Authorization'=$result.CreateAuthorizationHeader()
}
$URI = "https://management.azure.com/providers/microsoft.resources/checkresourcename?api-version=2014-01-01"
Invoke-RestMethod -Uri $URI -Method POST -Headers $authHeader -Body "{'Name':'<the name you want to test>','Type':'<the resource type you want to test>'}"
Upvotes: 7