LillaTheHun
LillaTheHun

Reputation: 141

How do I create a resource group in Azure using RESTful API in PowerShell?

I want to create an Azure Resource Group using a REST API call, but I can't seem to get the syntax right. Here's what I have:

$validateResourceGroupUri = 'https://management.azure.com/subscriptions/SUBSCRIPTION_ID/resourceGroups/' + $resourceGroupName + '/?api-version=2015-01-01'

try { $trapValidateResponse = Invoke-RestMethod -Method PUT -Headers $armHeaders -Uri $validateResourceGroupUri -Body $deploymentTemplate }
catch { throw $_ }

Where:

$deploymentTemplate = JSON deployment template (obviously)

$resourceGroupName = user-inputted RG name to be created

$armHeaders = @{ 'Authorization' = "Bearer $token"; 'Content-Type' = "Application/json" }

I have a feeling the issue resides in the -Body parameter, but I can't seem to find anything online detailing what exactly the call should consist of. I found THIS where, if you scroll down to "Create a resource group" section, it details some information, but that's unfortunately all I've been able to find. Any thoughts?

Upvotes: 1

Views: 1581

Answers (1)

Shui shengbao
Shui shengbao

Reputation: 19223

You could try to use the following commands to create a new resource group, it works for me.

##get token
$TENANTID="<your tenantid>"
$APPID="<>"
$PASSWORD="<>"
$result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TENANTID/oauth2/token?api-version=1.0 -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
$token=$result.access_token

##set subscriptionId and resource group name
$subscriptionId="<your subscriptionId >"
$resourcegroupname="<resource group name>"

$Headers=@{
  'authorization'="Bearer $token"
  'host'="management.azure.com"
}
$body='{
    "location": "northeurope",
     "tags": {
        "tagname1": "test-tag"
    }
 }'
Invoke-RestMethod  -Uri "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${resourcegroupname}?api-version=2015-01-01"  -Headers $Headers -ContentType "application/json" -Method PUT -Body $body

enter image description here

Upvotes: 3

Related Questions