Moving resources failed because resource group has active deployments - azure

When I try to change a website's resource group in Azure Powershell, I get the following error:
"Error": {
"Code": "MultipleErrorsOccurred",
"Message": "Multiple error occurred: Conflict,Conflict. Please see details.",
"Target": null,
"Details": [
{
"Code": "DeploymentActive",
"Message": "Moving resources failed because resource group 'rg1' has active deployments.",
"Target": null,
"Details": null
},
{
"Code": "DeploymentActive",
"Message": "Moving resources failed because resource group 'rg1' has active deployments.",
"Target": null,
"Details": null
}
}
I use the following commands:
$webapp = Get-AzureResource -ResourceGroupName "rg1" -ResourceName resourceName -ResourceType Microsoft.Web/sites
Move-AzureResource -DestinationResourceGroupName "rg2" -ResourceId $webapp.ResourceId
One solution is to delete and recreate the website but is there any other way that we can sort this problem out without deleting anything?

Move-AzureResource is obsolete now. Try using Move-AzureRmResource.
For the error, you will have to wait till an ongoing deployment in rg1 is complete.
You could retry once the deployment is complete.
Cheers!

Related

403 Error: Create & Assign Azure Policy Definition at Management Group Level using Terraform

provider "azurerm" {
features {}
}
data "azurerm_management_group" "management_group" {
display_name = var.management_group_display_name
}
resource "azurerm_policy_definition" "deployment_policy_definition" {
name = "resources-in-eastus-policy"
policy_type = "Custom"
mode = "All"
display_name = "Allowed to only deploy in East US location"
management_group_id = data.azurerm_management_group.management_group.id
policy_rule = <<POLICY_RULE
{
"if": {
"not": {
"field": "location",
"in": "[parameters('allowedLocations')]"
}
},
"then": {
"effect": "audit"
}
}
POLICY_RULE
parameters = <<PARAMETERS
{
"allowedLocations": {
"type": "Array",
"metadata": {
"description": "The list of allowed locations for resources.",
"displayName": "Allowed locations",
"strongType": "location"
}
}
}
PARAMETERS
}
resource "azurerm_management_group_policy_assignment" "mngmt_grp_dep_pol_assign" {
name = "assign-pol-to-mgmt-grp"
policy_definition_id = azurerm_policy_definition.deployment_policy_definition.id
management_group_id = data.azurerm_management_group.management_group.id
parameters = <<PARAMETERS
{
"allowedLocations": {
"value": [ "eastus" ]
}
}
PARAMETERS
}
Error: creating/updating Policy Definition "resources-in-eastus-policy": policy.DefinitionsClient#CreateOrUpdateAtManagementGroup: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailed" Message="The client 'live.com#XXX#gmail.com' with object id '0ab7dad7-dba2-46d9-8cc6-878647e9a5cb' does not have authorization to perform action 'Microsoft.Management/managementGroups/Microsoft.Management/1/Microsoft.Authorization/resources-in-eastus-policy/write' over scope '/providers/Microsoft.Management/managementGroups/providers/Microsoft.Management/managementGroups/1/providers/Microsoft.Authorization/policyDefinitions' or the scope is invalid. If access was recently granted, please refresh your credentials."
Azure Roles added for the owner/user of the azure-cli
The ID of the target management group where I am trying to create and assign the policy under the Tenant Root Group is 1
Error:
The client 'live.com#XXX#gmail.com' with object id
'0ab7daxxxxxxx-xxxxe9a5cb' does not have authorization to perform
action
'Microsoft.Management/managementGroups/Microsoft.Management/1/Microsoft.Authorization/resources-in-eastus-policy/write
As the error mentions the client doesn’t have proper RBAC role to perform policy definition creation on management groups.
Try to assign that ObjectId mentioned in the error , the proper role like Management Group Contributor OR Management Group Reader role.
Note: The principal/user which is deploying ,must have permissions like Contributor to create resources at the tenant scope and to assign that permission one must have Owner role
Also see below table from management-group-access :
From the management group , Go to Access control (IAM), add your client(user/service principal) as an RBAC role
or provide role through powershell:
New-AzRoleAssignment -Scope '/' -RoleDefinitionName 'Owner' -ObjectId <objectidofftheclient>
Then wait for some time for the role to reflect and then try to create policy assignment to management group:
Policy assignment made to management group.
Please make sure if the management group is reflected properly and check the id is correct in terraform, if it is already created in portal. Else import them using terraform import and then perform terraform operations.

Run a powershell script in a storage account using Terraform when building an azure vm

I am attempting to write terraform code which when the VM is being created the code will reach out to a storage account and run a powershell script. there seems to be some solutions to my answer but all the solutions I have found are using a public blob access. I have to disable enable blob public access. Below is my terraform code and error
resource "azurerm_virtual_machine_extension" "powershell" {
count = length(var.instances)
name = "runpowershell"
virtual_machine_id = azurerm_windows_virtual_machine.vm.*.id[count.index]
depends_on = [azurerm_windows_virtual_machine.vm]
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.9"
settings = <<SETTINGS
{
"fileUris": ["https://test.blob.core.windows.net/scripts/deployment.ps1"],
"commandToExecute": "powershell -ExecutionPolicy Unrestricted -file deployment.ps1"
}
SETTINGS
I changed the code to
``{
"fileUris": ["https://test.blob.core.windows.net/scripts/deployment.ps1"]
}
SETTINGS
protected_settings = <<PROTECTED_SETTINGS
{
"storageAccountKey": "Vg/4BBah3......ASt2sbGww==",
"storageAccountName": "test",
"commandToExecute": "powershell -ExecutionPolicy Unrestricted -File deployment.ps1"
}
PROTECTED_SETTINGS
}
now i get the message - which reads Forbidden now not conflict - I checked the key and it is correct
Error: Code="VMExtensionProvisioningError" Message="VM has reported a failure when processing extension 'runpowershell'. Error message: "Failed to download all specified files. Exiting. Error Message: The remote server returned an error: (403) Forbidden."\r\n\r\nMore information on troubleshooting is available at https://aka.ms/VMExtensionCSEWindowsTroubleshoot "
Well, I found my answer. In the code I pasted I changed the name of the actual storage account. In my code for fileurs I had the correct name but for storage account in protected settings I spelled the account wrong. Once I fixed that...it all worked.

How to add Custom Role for “Virtual Machine operator” to set Auto-shut down

I want to create a custom role in Azure to allow "Virtual machine operator" to set Auto-shutdown time.
I tried creating a custom role using JSON but don't know which is the action for "Auto-shutdown"
{
"Name": "Virtual Machine Operator 2",
"IsCustom": true,
"Description": "Can deallocate, start and restart virtual machines.",
"Actions": [
"Microsoft.Compute/*/read",
"Microsoft.Compute/virtualMachines/start/action",
"Microsoft.Compute/virtualMachines/restart/action",
"Microsoft.Compute/virtualMachines/deallocate/action",
"Microsoft.Compute/Auto-shutdown/*"
],
"NotActions": [
],
"AssignableScopes": [
"/subscriptions/8c18015f-f6be-403d-905d-5cdfcb1f1c1d"
]
}
The line in above JSON is incorrect
"Microsoft.Compute/Auto-shutdown/*"
If you enable the Auto-shutdown for the VM, the Azure will create a resource whose resource type is Microsoft.DevTestLab/schedules in the resource group the VM located. You could check it in the resource group(choose the Show hidden types option).
So if you want to set the Auto-shutdown time, you will need the Microsoft.DevTestLab/schedules/* permission(maybe the Microsoft.DevTestLab/schedules/write is the minimum permission, I have just test Microsoft.DevTestLab/schedules/*).
Meanwhile, when we set the Microsoft.DevTestLab/schedules, we also actually set the VM(the resource is linked to the VM scope), so we also need the Microsoft.Compute/virtualMachines/write permission, otherwise you will get an error.
In conclusion, the custom role .json file should be like below.
{
"Name": "Virtual Machine Operator 2",
"IsCustom": true,
"Description": "Can deallocate, start and restart virtual machines.",
"Actions": [
"Microsoft.Compute/*/read",
"Microsoft.Compute/virtualMachines/start/action",
"Microsoft.Compute/virtualMachines/restart/action",
"Microsoft.Compute/virtualMachines/deallocate/action",
"Microsoft.DevTestLab/schedules/*",
"Microsoft.Compute/virtualMachines/write"
],
"NotActions": [
],
"AssignableScopes": [
"/subscriptions/xxxxxxxxxxxxxxxx"
]
}
Besides, I test the custom role to set the Auto-shutdown setting with a service principal context in the powershell, it works fine on my side, you could also have a try.
$resourcegroup = "<resource group name>"
$vm = "<VM Name>"
$shutdown_time = "1900"
$shutdown_timezone = "China Standard Time"
$properties = #{
"status" = "Enabled";
"taskType" = "ComputeVmShutdownTask";
"dailyRecurrence" = #{"time" = $shutdown_time };
"timeZoneId" = $shutdown_timezone;
"notificationSettings" = #{
"status" = "Disabled";
"timeInMinutes" = 30
}
"targetResourceId" = (Get-AzVM -ResourceGroupName $resourcegroup -Name $vm).Id
}
Set-AzResource -ResourceId ("/subscriptions/{0}/resourceGroups/{1}/providers/microsoft.devtestlab/schedules/shutdown-computevm-{2}" -f (Get-AzContext).Subscription.Id, $resourcegroup, $vm) -Properties $properties -Force

Terraform - Provision VM Extensions with Parameters

I'm trying to provision two Azure Virtual Machine Extensions, that have parameters associated to them:
Microsoft Antimalware
Site24x7 Agent for Windows Server Monitoring
I could not find much documentation, but I tried to extract the data from the azure portal under Automation script to see how it was setup in JSON template.
resource "azurerm_virtual_machine_extension" "test1" {
name = "IaaSAntimalware"
location = "${azurerm_resource_group.test.location}"
resource_group_name = "${azurerm_resource_group.test.name}"
virtual_machine_name = "${azurerm_virtual_machine.testapp.name}"
publisher = "Microsoft.Azure.Security"
type = "IaaSAntimalware"
type_handler_version = "1.5.5.1"
auto_upgrade_minor_version = "true"
settings = <<SETTINGS
{
"AntimalwareEnabled": true,
"RealtimeProtectionEnabled": "true",
"ScheduledScanSettings": {
"isEnabled": "true",
"day": "1",
"time": "120",
"scanType": "Quick"
},
"Exclusions": {
"Extensions": "",
"Paths": "",
"Processes": ""
}
}
SETTINGS
tags {
environment = "${var.tag_env}" }
}
Azure Portal Configuration for Antimalware Extension
azurerm_virtual_machine_extension.test1: 1 error(s) occurred:`
azurerm_virtual_machine_extension.test1: compute.VirtualMachineExtensionsClient#CreateOrUpdate: Failure sending request: StatusCode=400 -- Original Error: autorest/azure: Service returned an error. Status=400 Code="InvalidParameter" Message="The value of parameter typeHandlerVersion is invalid."
Does anyone know the proper syntax?
If you look at this line in the anti-malware-extension-windows-vm sample of azure-quickstart-templates: "typeHandlerVersion": "1.1", you see that you are passing the wrong value for the version.

Defining Azure VM CustomScriptExtension in Terraform (Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. \".")

I defined a CustomScriptExtension for Azure VM in Terraform:
resource "azurerm_virtual_machine_extension" "test" {
name = "WinRM"
location = "South Central US"
resource_group_name = "${azurerm_resource_group.test.name}"
virtual_machine_name = "${azurerm_virtual_machine.test.name}"
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.8"
settings = <<SETTINGS
{
"fileUris": "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1",
"commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File ConfigureRemotingForAnsible.ps1"
}
SETTINGS
}
However I get (the same error is visible in Azure portal in VM extensions):
azurerm_virtual_machine_extension.test: compute.VirtualMachineExtensionsClient#CreateOrUpdate: Failure sending request: StatusCode=200 -- Original Error: Long running operation terminated with status 'Failed': Code="VMExtensionProvisioningError" Message="VM has reported a failure when processing extension 'WinRM'. Error message: \"Invalid handler configuration. Exiting. Error Message: Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. \"."
The same parameters executed as an Azure deployment works with no problems (relevant excerpts below):
"fileUris": {
"type": "string",
"defaultValue": "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1",
"metadata": {
"description": "The uri list of files. Split by a space."
}
},
"settings": {
"fileUris": "[split(parameters('fileUris'), ' ')]",
"commandToExecute": "[parameters('commandToExecute')]"
}
Am I missing something, or is it a bug in Terraform?
Some debugging:
If I replace the settings with just:
{
"commandToExecute": "mkdir C:\\Test"
}
the directory gets created, so the problem is with fileUris.
If I replace fileUris in the settings JSON with fileUri (which should be wrong):
{
"fileUri": "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1",
"commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File ConfigureRemotingForAnsible.ps1"
}
there is no the Encountered 'Text' with name '', namespace ''. \". error, powershell.exe fires and reports missing ConfigureRemotingForAnsible.ps1.
Error message: \"Invalid handler configuration. Exiting. Error Message: Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. \"."
As I known, the value type of fileUris should be an array, I have tested it with Azure deployment, if I configure fileUris as a string value, then I could get the same error as you provided.
UPDATE
The fileUris should look like as follows:
"settings": {
"fileUris": [
"https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
],
"commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File ConfigureRemotingForAnsible.ps1"
}
Here is an terraform example , just copy-paste it... I commented the RG section along with location ( from case to case, you might not need it ) :
resource "azurerm_virtual_machine_extension" "win-installansibleclient" {
name = "${var.current-name-convention-core-module}-mtwin-installansibleclient"
#location = "${var.preferred-location-module}"
#resource_group_name = "${var.current-name-convention-core-module}-rg"
virtual_machine_id = "${azurerm_virtual_machine.dcaddns-w2k16.id}"
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.8"
settings = <<SETTINGS
{
"fileUris": [
"https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
],
"commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File ConfigureRemotingForAnsible.ps1"
}
SETTINGS
}

Resources