Problem: When I run a Powershell runbook with an 'Invoke-AzureRmVMRunCommand' on an Azure Windows VM, and I have to STOP the runbook because of an error in the invoked command (and it idles forever), all new repetitions of the runbook fail with "Run command extension execution is in progress. Please wait for completion before invoking a run command.".
This is the runbook statement to have a PS script running on the VM:
Invoke-AzureRmVMRunCommand -ResourceGroupName $objVM.ResourceGroupName -Name $objVM.Name -CommandId 'RunPowerShellScript' -ScriptPath $strRemoteScriptFileNameTmp -Parameter $hshParams
The PS code in '$strRemoteScriptFileNameTmp' has this statement in it, which makes the runbook idling, ,i.e. need to be fixed:
Invoke-Expression -Command "$strRunTimeEnv $strExecPath $strExecParaString"
The -Command then looks as this; it shall install that ODBC driver to the VM, and works when executed with the PS CLI of the VM (RDP'd):
msiexec.exe /quiet /passive /qn /norestart /l* D:\msodbcsql_13.0_x64.log /package D:\UpdateODBC\Application\Live\msodbcsql_13.0_x64.msi IACCEPTMSODBCSQLLICENSETERMS=YES ADDLOCAL=ALL
Question: I know there is a timeout of 90 minutes for that (orphaned) command of the runbook. But, where is this idling, on the VM or the Automation Account? And, how can I kill it? It seems ridiculous to wait for 90 minutes before a new attempt to run the runbook can be made.
(I am not exactly get into a productive workflow here the way Msft have set this up... And yes, I read the posts on this topic already, and also the Msft docs which really need proof-reading by an English speaker, btw.)
To conclude this I just like to share what I was given by MSDN in their answer:
"...Invoke-AzureRmVMRunCommand is actually using a REST command to send a powershell script to the VM..."
"There are restrictions on what can be done via this method:
One script at a time can run.
You can't cancel a running script.
The maximum time a script can run is 90 minutes. After that, it will time out.
"
See:
[https://learn.microsoft.com/en-us/azure/virtual-machines/windows/run-command#restrictions][1]
Best!
Related
I have an issue at PowerShell script for executing on pipeline at dev azure,
error is happening with message:
Start-Process : This command cannot be run due to the error: %1 is not a valid Win32 application
it was worked some time ago but now it is not, is it some updates were done on azure?
or I need to improve some code?
foreach ($alert in $alerts)
{
Write-Log "`tCreating alert $($alert.AlertName)"
$azArgs = "monitor metrics alert create --name ""$($alert.AlertName)"" --resource-group ""$($resourceGroup)"" --condition ""$($alert.AlertRule)"" --scopes ""$($alert.ResourceId)"" --window-size 5m --evaluation-frequency 1m --action ""$actionGroupResourceId"" --description "" "" --subscription ""$subscriptionId"" --auto-mitigate true"
Write-Verbose $azArgs
Start-Process "az" -ArgumentList $azArgs -NoNewWindow -Wait
}
Start-Process : This command cannot be run due to the error: %1 is not a valid Win32 application
AFAIK, the issue shows that you are not using X32 environment. so, that the error thrown. It is a common issue we cannot directly find out what exactly happens we can fix it by following
Ways to fix:
Try to uninstall and install the PowerShell Az module.
Update the PowerShell Az module with latest version
Check your Dev environment has X64. If it is X64 make sure to install the PowerShell Module Globally.
It may happen sometimes with you are passing environment variable path make sure to double check once.
issue is related to azure updates https://pullanswer.com/questions/error-with-startprocess-and-az-command
problem is Azure Cli has been updated and so now there is an az.ps1 so i need to make "az.cmd" in order to continue to call the good program...
I have a windows Azure VM and need to execute “%windir%\system32\sysprep” and then execute “sysprep /generalize” both from admin mode from my local machine through Powershell. How can I do that ?
For your requirements, as I know you can use a PowerShell script to achieve it. First, you can take a look at the Sysprep, it can be run in a PowerShell command C:\WINDOWS\system32\sysprep\sysprep.exe /generalize /shutdown /oobe. Put this command inside a script, then you can use two ways to run this script in the VM from your local machine. One is that use the Invoke command.
In Azure CLI:
az vm run-command invoke --command-id RunPowerShellScript -g group_name -n vm_name --scripts #script.ps1
In PowerShell:
Invoke-AzVMRunCommand -ResourceGroupName 'rgname' -VMName 'vmname' -CommandId 'RunPowerShellScript' -ScriptPath 'sample.ps1'
Another is that use the VM extension. It's a little complex. You can take a look at the Azure PowerShell command Set-AzVMCustomScriptExtension.
Output after running:-
Value[0] :
Code : ComponentStatus/StdOut/succeeded
Level : Info
DisplayStatus : Provisioning succeeded
Message :
Value[1] :
Code : ComponentStatus/StdErr/succeeded
Level : Info
DisplayStatus : Provisioning succeeded
Message :
Status : Succeeded
Capacity : 0
Count : 0
I could't make sysprep work with Invoke-AzVMRunCommand, It run with succeeded status, but the VM was not shutdown.
Finally found https://developercommunity.visualstudio.com/t/devops-sysprep-public-agents/1375989 and it make sense.
So just use Invoke-AzVMRunCommand to run sysprep won't work, I am thinking to reset a local admin user password and run the process as local admin might be a workaround.
My (dotNET) application is built (using a Windows Hosted agent), from a build pipeline, and in the subsequent Release pipeline, I provision a 16GB-Win2016 VM (enabling RDP, HTTP, HTTPS, WinRM and SSH), into which I RDP manually (there is a Manual Intervention task here), and configure WinRM (following this article: https://learn.microsoft.com/en-us/azure/marketplace/cloud-partner-portal/virtual-machine/cpp-configure-winrm-after-vm-creation#configure-vm-to-enable-winrm). Everything is fine until here. The next task is a Azure File Copy task, which essentially copies the Build artifacts (from $(System.DefaultWorkingDirectory)) and pastes into a directory I specify. Works like a charm. The next task I have is to create a VHD of this whole VM (essentially after the copying is done).
I know I can manually RDP into the VM (again) and sysprep (with oobe/generalize/shutdown), then maybe go back to the Azure Portal and Disk Export the OS Disk (specifying the SAS URL expiration time at whatever (36000 per the article)) BUT can this all be automated?
So, long story short - I'd like to know if sysprep oobe/generalize/shutdown can be performed remotely preferably over a PS task. I understand the other part of it (exporting the disk and all) can be, but if sysprep can be done remotely nothing like it.
I tried this and got what I wanted:
$sysprep= 'C:\Windows\System32\Sysprep\Sysprep.exe'
$arg1 = '/generalize'
$arg2 = '/oobe'
$arg3 = '/shutdown'
$arg4 = '/quiet'
& $sysprep $arg1 $arg2 $arg3 $arg4 -Wait
Make sure you do NOT use Azure custom script extension to run sysprep.
Azure scripts run under the LocalSystem user context: source
Custom Script Extension will run under the LocalSystem Account
This is problematic because sysprep does NOT support running under a system user context: source
Sysprep cannot be run under the context of a System account. Running Sysprep under the context of System account by using Task Scheduler or PSExec, for example, is not supported.
Providing this so that people avoid my mistake :)
So, you dont have to configure winrm manually, you can script it\configure it while provisioning the vm. and if\when winrm is working you can just use powershell remoting to issue a command against the vm with:
Invoke-Command -ComputerName dnsname\ipaddress_goes_hehe
-ScriptBlock { sysprep /shutdown /generalise}
https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-winrm-windows
You can implement this using an Azure custom script extension. There is a github project:
https://github.com/jlongo62/AzureVMToImage containing powershell scripts to image a VM. These scripts were built to preserve VM when creating an image, instead of destroying the original VM. The scripts can be called from Azure Devops. There is no need to authenticate against the VM.
The meat of what you need is:
1- create a storageaccount blob containing the following script (the -Wait is very important):
Start-Process -FilePath C:\Windows\System32\Sysprep\Sysprep.exe -ArgumentList '/generalize /oobe /quiet /quit' -Wait
2 - invoke it on the VM:
$response = Set-AzureRmVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Location $vm.Location `
-Name $ExtensionName `
-FileUri $blobUri `
-Run $FileName
I have an Azure runbook that runs on schedule. Its in powershell and this runbook starts a VM and executes a script on the VM started. How I achieve this is
1) Store the script to be run on the VM in a storage account
2) Run powershell runbook
3) Powershell runbook uses wget command to copy the script from step 1
4) Invoke-AzureRmVMRunCommand in the Azure automation powershell commands as shown below
wget "https://utilitystorageaccnt.blob.core.windows.net/utilitycontainer/token" -outfile ((Get-Location).path + "\Reporting Copy.ps1") -UseBasicParsing
Invoke-AzureRmVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VmName -CommandId 'RunPowerShellScript' -ScriptPath ((Get-Location).path + '\Reporting Copy.ps1') -ErrorVariable result
Please not that the above two commands are in the powershell runbook script and not the actual script that is run on the VM.
Facing two issues
1) When this script Reporting Copy.ps1 runs standalone on the VM, then it works properly and it has no issues. When it is run using the runbook, I get these errors in the log file on the target vm.
"New-AzStorageContext : The term 'New-AzStorageContext' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again."
2) Even after this error occurs, it doesnt terminate and runs in loops. This script does a copy operation and it keeps looping until all the copy is complete. I can handle code to terminate but I would like to know how to force terminate a runbook. I tried to stop the VM for even a hour and it resumes the copy operation. The runbook status in Azure shows as completed. There are two python processes that show in explorer and terminating them doesn't work either.
Any help or hint is appreciated.
Thanks.
Look like you did not imported Az PowerShell module into our Automation Account.
Please, follow this tutorial : Az module support in Azure Automation
Try to use only Az module and not AzureRM
The issue was because I had not installed the AZ module for all users like this.
Install-Module -Name Az -AllowClobber -Scope AllUsers
Instead I had used
Install-Module -Name Az -AllowClobber -Scope CurrentUser
and since the automation runs on a different user, the issue occurred. Thanks for your help.
I have found azure slot swapping via powershell seems to be unrealiable (I imagine it is giving an error response that I can't see or is silently failing but claiming success). The slots being swapped are between two non production slots as shown in the script. About 10% of the time it seems to succeed. Im not sure why it succeeds or fails, hopefully someone can shed some light on what I am doing wrong here.
I have a script I have made that runs on a build job on Teamcity and the script is as follows:
param ([string]$publishFilePath = "%system.teamcity.build.checkoutDir%\3.
deployment\Fu.publishsettings")
Import-AzurePublishSettingsFile $publishFilePath;
Select-AzureSubscription "Visual Studio Professional with MSDN";
Set-AzureSubscription -SubscriptionName "Visual Studio Professional with MSDN";
Switch-AzureWebsiteSlot -Name FuWebsite -Slot1 Build-Automation -Slot2 Staging -Force -Verbose
Switch-AzureWebsiteSlot -Name FuServices -Slot1 Build-Automation -Slot2 Staging -Force -Verbose
The only logs I get are:
[10:20:12][Step 5/5] VERBOSE: Performing the operation "Swapping website
production slot ..." on
[10:20:12][Step 5/5] target "FuWebsite".
[10:21:16][Step 5/5] VERBOSE: Performing the operation "Swapping website production slot ..." on
[10:21:16][Step 5/5] target "FuMeServices".
[10:22:19][Step 5/5]
[10:22:19][Step 5/5]
[10:22:19][Step 5/5] Process exited with code 0
About 10% of the time it seems to succeed. Im not sure why it succeeds or fails
If you not sure whether it succeed or fail. I would suggest you test below code with -Debug mode.
Switch-AzureWebsiteSlot -Name FuWebsite -Slot1 Build-Automation -Slot2 Staging -Force -Verbose -Debug
Here is the result I get on my side:
The detailed information will help you to find out the solution.
In addtion, if you execute the swap command, however the site does not change. Please try to clean IE sessions and cookies then try again. Or use KUDU to see the original file is changed or not.