I have been provisioning machines over an over trying to learn all the VM Extensions. One of the extensions that I have been playing with is the DSC extension. Every time I provision with this extension, it adds an additional record into the State Configuration, resulting in many stale machines. I wanted to clear out all the old machines. I couldn’t find a way to do it in PowerShell, so I figure out how to do it via the REST API (and PowerShell).
Here is the code to remove all machines from Azure State Configuration (DSC)
$SubscriptionId = "$($env:SubscriptionId)"
$TenantId = "$($env:TenantId)"
$ClientID = "$($env:ClientID)"
$ClientSecret = "$($env:ClientSecret)"
$TenantDomain = "$($env:TenantDomain)"
$loginURL = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$resource = "https://management.core.windows.net/"
$resourceGroupName = "YourResourceGroupName "
$automationAccountsName ="YourAutomationAccountsName "
# get the OAUTH token & prepare header
$body = @{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret}
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL -Body $body
$headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}
# main query to find all the nodes
$url="https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Automation/automationAccounts/$automationAccountsName/nodes?api-version=2018-01-15"
$results=Invoke-RestMethod -Uri $url -Headers $headerParams -Method Get
# Loop through all the nodes and delete them all.
foreach ($node in $($results.value | Select-Object -ExpandProperty properties | Select nodeid)){
$url="https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Automation/automationAccounts/$automationAccountsName/nodes/$($node.nodeId)?api-version=2018-01-15"
Invoke-RestMethod -Uri $url -Headers $headerParams -Method Delete
}
Notes:
- I put all my SPN info into environmental varaibles (easier to switch of needed)
- Put in your RG name and Auutomation Account Name
- Warning. This will delete all nodes!
HTH