Azure powershell Move-AzureDeployment - error: HttpRequestException - azure

We have a Cloud Service (Classic) swap using powershell in Azure pipelines that has worked all year, setup by a previous employee and now it is failing with error:
Move-AzureDeployment : An error occurred while sending the request.
At D:\a\_temp\blahblahblah.ps1:8 char:1
+ Move-AzureDeployment -ServiceName $servicename
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Move-AzureDeployment], HttpRequestException
+ FullyQualifiedErrorId : System.Net.Http.HttpRequestException,Microsoft.WindowsAzure.Commands.ServiceManagement.H
ostedServices.MoveAzureDeploymentCommand
The actual job task is using PowerShell Script set as inline with Error action as Stop. The actual script:
$subid = 'blah-blah-blah-blah'
$servicename = "blahblahblah"
Select-AzureSubscription -SubscriptionId $subid
Move-AzureDeployment -ServiceName $servicename
$service = Get-AzureDeployment -ServiceName $servicename -Slot Production
Start-Sleep -s 300
Remove-AzureDeployment -ServiceName $servicename -Slot "Staging" -Force
I was sure this was maybe a Service connection with Management Certificate expired but I have one valid working and found it is setup exactly like another similar pipeline/service connection that is working.

So the issue was two things, SSL and PowerShell version issues after updates. To deal with SSL issues I added this line to the top of our inline script:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
And for the PowerShell issue it required changing to the Azure PowerShell app for pipelines, so we could roll back to a specific task version and the 4.2.1 PowerShell Version as seen in this answer:
Programmatically Swap Staging Slot to Production Slot in Azure Cloud Service
This might be the only way to swap a Cloud Service (Classic) these days. A little annoying Azure pushed this classic service and never properly maintained it.

Related

Getting error in azure powershell while creating new storage account using the command New-AzStorageAccount

$storageAccount = New-AzStorageAccount -ResourceGroupName $resourceGroup -Name "blobstgaccdemo" -SkuName Standard_LRS -Location $location
New-AzStorageAccount : An error occurred while sending the request.
At line:1 char:19
+ ... geAccount = New-AzStorageAccount -ResourceGroupName $resourceGroup -N ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzStorageAccount], HttpRequestException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Management.Storage.NewAzureStorageAccountCommand
This is a generic error and can occur in more than a few conditions, including when Azure PowerShell is not able to reach/resolve the underlying management REST APIs, or in case of SSL errors.
To get more information about the error, run the PS cmdlet passing the -Debug parameter along, or set $DebugPreference to Continue before executing the cmdlet. This would surface the details of the exception along with the stack trace.
If this is consistently happening with other cmdlets as well, then you could try upgrading PS modules, or re-installing Azure PowerShell itself. Another quick alternative would be to use Azure Cloud Shell that is preconfigured with all the required modules.

Powershell Script continues to ask me to use Select-AzureSubscription although I have called it

I have an Azure runbook where I am trying to deallocate VMs. When I run the runbook I get the error
Stop-AzureVM : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to
set the default subscription.
I have used the below in my script.
Add-AzureRmAccount
Select-AzureRMSubscription
After calling the select, it prints out
PSComputerName : localhost
PSSourceJobInstanceId :
Account :
Environment :
Subscription :
Tenant :
with the correct subscrption and tenant information so it seems the select is working correctly, but for some reason I still cannot use the Stop-AzureVM cmdlet.
Any ideas?
The command Stop-AzureVM is Azure Service Management PowerShell command. It just can be used to stop Azure classic VM. But the command Add-AzureRmAccount is Azure Resource Management PowerShell command. After running the command, we just can manage Azure Resource Management resources. For more details, please refer to here and here.
So with Azure ARM VM, please use the command Stop-AzureRmVM to stop it. Meanwhile, regarding how to stop Azure classic VM, please refer to the following steps
Create Azure Classic Run As Account
Script
$ConnectionAssetName = "AzureClassicRunAsConnection"
# Get the connection
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
# Authenticate to Azure with certificate
$CertificateAssetName = $Conn.CertificateAssetName
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
#stop VM
Stop-AzureVM -ServiceName "ContosoService01" -Name "MyVM" -Force
Besides, regarding how to check if the VM is classic, please refer to the blog
Try Running the below :
Get-Module AzureRm.Profile -ListAvailable
This issue might occur when there is multiple instances of the module. If there are multiple instance remove the older modules and retain the new module.
To remove the old module : Uninstall-Module -Name AzureRm.Profile -RequiredVersion 4.6.0#(olderversion if you have any)

Octopus deploy in azure blue and green environments

I am trying to deploy an app service in azure using octopus for blue and green environments.
It all work apart of the step that tries to swap.
Here are my steps,
Step 1
New-AzureRmWebAppSlot -ResourceGroupName quantum-apps-dev -Name QuantumDev -Slot green
Step 2
Deploy app service
Step 3
Switch-AzureWebsiteSlot –Name QuantumDev -Slot1 "green" -Force
Step 4
Remove-AzureRmResource -ResourceGroupName quantum-apps-dev -ResourceType Microsoft.Web/sites/slots –Name QuantumDev/green -Force
However step 3 is failing with the following error,
Calamari.exe : CloseError: No default subscription has been designated. Use Select-AzureSubscription -Default to set the default subscription.
I have added the suggested command above but still failing and complaining that cannot find the subscription
Any ideas? Thanks
Try to use Switch-AzureRmWebsiteSlot instead of Switch-AzureWebsiteSlot.
Both of them are used to swap the production slot for a website with another slot.
As you are using New-AzureRmWebAppSlot successfully, the AzureRM module means work well.
So try to use Switch-AzureRmWebsiteSlot.

Azure DevOps Powershell script Could not create SSL/TLS secure channel

Problem:
If I call command Get-AzureDeployment(also Get-AzureService) from 'Azure Powershell' task in DevOps Pipeline I am getting: 'The request was aborted: Could not create SSL/TLS secure channel.'
Introduction:
I use Azure DevOps to deploy Azure Cloud service (classic) into Azure
The 'Azure Powershell' task was working the whole time but then without changing anything it stopped working
I have also imported the certificate(used by DevOps) into my pc (by Import-AzurePublishSettingsFile) and tried to run the same powershell script and everytnig works fine so I expect problem in DevOps
DevOps connection:
I have created 'Service connection' in Azure DevOps to connect into Azure
The Service
connection is type of 'Azure Classic' (because 'Azure Resource Manager' is not for 'Cloud service classic')
Autentication method of the
'Azure Classic service connection' is 'Certificate based'.
I used
certificate generated by 'Publish Settings File' for my azure
subscription. The certificate was placed by azure into
My-subscription->Management certificates (expiration date is in mid
2021)
I use this service connection for deploying app (Cloud service classic) into Azure with no problem (by DevOps task 'Azure Cloud Service deployment') but just the 'Azure Powershell' task start failing.
This all was working for 3 months and then stopped working for any reason.
The weird thing is that when I was playing with DevOps to find out what is wrong the task was once successfully run, but when I tried that again I got the error again.
I have both logs, from sucessful call and failing call. 2506 lines of logs are identical and the change is after this line.
I can send you both full logs but I don't want to place here so long logs.
Successful try:
VERBOSE: 8:31:40 AM - Begin Operation: Get-AzureDeployment
VERBOSE: 8:31:42 AM - Completed Operation: Get-AzureDeployment
... some other info about the deployment in slot
Log from failing call:
VERBOSE: 9:53:39 AM - Begin Operation: Get-AzureDeployment
##[debug]Caught exception from task script.
##[debug]Error record:
##[debug]Get-AzureDeployment : An error occurred while sending the request.
##[debug]At D:\a\r1\a\_Tools\Powershell\cloud-service_swap-slot.ps1:14 char:15
##[debug]+ ... eployment = Get-AzureDeployment -Slot "Staging" -ServiceName $CloudSe ...
##[debug]+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
##[debug] + CategoryInfo : CloseError: (:) [Get-AzureDeployment], HttpRequestException
##[debug] + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices.GetAzureDeploymentComma nd
##[debug]
##[debug]Script stack trace:
##[debug]at <ScriptBlock>, D:\a\r1\a\_Tools\Powershell\cloud-service_swap-slot.ps1: line 14
##[debug]at <ScriptBlock>, <No file>: line 1
##[debug]at <ScriptBlock>, D:\a\_tasks\AzurePowerShell_72a1931b-effb-4d2e-8fd8-f8472a07cb62\3.171.2\AzurePowerShell.ps1: line 145
##[debug]at <ScriptBlock>, D:\a\_tasks\AzurePowerShell_72a1931b-effb-4d2e-8fd8-f8472a07cb62\3.171.2\AzurePowerShell.ps1: line 141
##[debug]at <ScriptBlock>, <No file>: line 1
##[debug]at <ScriptBlock>, <No file>: line 22
##[debug]at <ScriptBlock>, <No file>: line 18
##[debug]at <ScriptBlock>, <No file>: line 1
##[debug]Exception:
##[debug]System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
##[debug] at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
##[debug] at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
##[debug] --- End of inner exception stack trace ---
##[debug] at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
##[debug] at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
##[debug] at Microsoft.WindowsAzure.Management.Compute.DeploymentOperationsExtensions.GetBySlot(IDeploymentOperations operations, String serviceName, DeploymentSlot deploymentSlot)
##[debug] at Microsoft.WindowsAzure.Commands.Utilities.Common.ServiceManagementBaseCmdlet.ExecuteClientActionNewSM[TResult](Object input, String operationDescription, Func`1 action, Func`3 contextFactory)
##[error]An error occurred while sending the request.
##[debug]Processed: ##vso[task.logissue type=error]An error occurred while sending the request.
##[debug]Processed: ##vso[task.complete result=Failed]
In both logs I can also find this for adding Azure account into Powershell:
##[debug]Added certificate to the certificate store.
##[command]Set-AzureSubscription -SubscriptionName PXX -SubscriptionId XXXXXX01-09f5-4703-bcc9-6ff914XXXXXX -Certificate ******** -Environment AzureCloud
##[command]Select-AzureSubscription -SubscriptionId XXXXXX01-09f5-4703-bcc9-6ff914XXXXXX
##[debug]Leaving Initialize-Azure.
## Initializing Azure Complete
(I have replaced some strings with X)
There is the Powershell task in YAML:
steps:
- task: AzurePowerShell#3
displayName: 'Swap slots'
inputs:
azureConnectionType: ConnectedServiceName
azureClassicSubscription: 'PXX subscription'
ScriptPath: '$(System.DefaultWorkingDirectory)/_Tools/Powershell/cloud-service_swap-slot.ps1'
ScriptArguments: '-CloudServiceName $(CloudServiceName)'
FailOnStandardError: true
azurePowerShellVersion: LatestVersion
And the Powershell script for swapping slots that works from local pc (with the same cert) but failing in DevOps:
[CmdletBinding(PositionalBinding=$True)]
Param(
[Parameter(Mandatory = $true)]
[String]$CloudServiceName # required
)
# Check if Windows Azure Powershell is avaiable
if ((Get-Module -ListAvailable Azure) -eq $null)
{
throw "Windows Azure Powershell not found! Please install from http://www.windowsazure.com/en-us/downloads/#cmd-line-tools"
}
# VIP Swap
$Deployment = Get-AzureDeployment -Slot "Staging" -ServiceName $CloudServiceName #It's failing here
if ($Deployment -ne $null -AND $Deployment.DeploymentId -ne $null)
{
Write-Output ("Current Status of staging in {0}" -f $CloudServiceName);
Write-Host ($Deployment | Select-Object -Property * -ExcludeProperty Configuration,RolesConfiguration | Format-List | Out-String);
$MoveStatus = Move-AzureDeployment -ServiceName $CloudServiceName
Write-Output ("Vip swap of {0} status: {1}" -f $CloudServiceName, $MoveStatus.OperationStatus)
}else
{
Write-Output ("There is no deployment in staging slot of {0} to swap." -f $CloudServiceName)
}
Does anyone the same experience like me? Where could be the problem?
# Update
I have tried to add this security protocol setting at the begining of the script but with the same error.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
This appears to be an issue with the Microsoft build agents, but adding the following code to the beginning of each Azure Powershell task seems to have resolved this for us until they can figure that out.
$pcert = (Get-Variable Endpoint -ValueOnly).Auth.Parameters.certificate
$bytes = [convert]::FromBase64String($pcert)
[IO.File]::WriteAllBytes("C:\cert.pfx",$bytes)
$null = Import-PfxCertificate -FilePath C:\cert.pfx -CertStoreLocation cert:\CurrentUser\My
There are few workarounds which are working.
Workaround 1
Use Azure Powershell Task Version 5
Select "Azure Resource Manager Connection"
Change ASM Module commands to Az commands
Workaround 2
Use Azure Powershell Task Version 3
Classic Connection
Downgrade Azure Powershell Version to 4.2.1
Workaround 3 (for private agents)
Create a self-signed cert in your CurrentUser\My store. you can find details on creating a self-signed cert here: https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-certs-create
Export the public key for the cert as a DER-encoded CER file (you can use mmc or any other cert tool for this)
Upload the .Cer file as a management certificate through the portal: https://learn.microsoft.com/en-us/previous-versions/azure/azure-api-management-certs
Authenticate using Set-AzureSubscription:
PS C:\> Clear-AzureProfile
PS C:\> $cert = Get-Item Cert:\CurrentUser\My\
PS C:\ > Set-AzureSubscription -SubscriptionName "" -SubscriptionId -Certificate $cert
PS C:\> Select-AzureSubscription -SubscriptionId
Workaround 4
Add below script to each Azure Powershell task
$p = (Get-Variable Endpoint -ValueOnly).Auth.Parameters.certificate
$bytes = [convert]::FromBase64String($p)
[IO.File]::WriteAllBytes("C:\cert.pfx",$bytes)
Import-PfxCertificate -FilePath C:\cert.pfx -CertStoreLocation cert:\CurrentUser\My
.
.
actual script
.
.
#remove certificate from store
$thumb = (Get-PfxData -FilePath "C:\cert.pfx").EndEntityCertificates.Thumbprint
Remove-Item -Path cert:\CurrentUser\My\$thumb -recurse -Force
We had the same issue. It only manifested on windows-2019 agents, not vs2017-win2016.
So you could fix it by changing the agent type, but a better fix is to use a specific Powershell version of 5.1.1 instead of latest. It seems that latest recently increased to 5.3.0 which causes this error.
I have the same issue and tried all these, for me it worked only if I added this after the Initialize-Azure part: "Set-AzureSubscription -SubscriptionId [my subscription id] -CurrentStorageAccountName [storage name]"
This issue is caused by a change of behavior introduced with the .NET September update. The following code will restore implicit storage of keys (the previous .Net 4.x behavior) through an environment variable:
Set-Item env:\COMPLUS_CngImplicitPersistKeySet 1
NOTE: You will then need to create a new publishsettings file, as the old certificate and keys will not be overwritten by a subsequent import.
Downgrading the Az Powershell version to 4.2.1 works using the AzurePowerShell#3 task.
In my case I had this problem in a Get-AzureServiceRemoteDesktopExtension command in a "Run Inline Azure Powershell" task on our on-premises Team Foundation Server 2017.
I tried adding the line #damien-caro suggested here ...
Set-Item env:\COMPLUS_CngImplicitPersistKeySet 1
... to my script, but that only solved the problem for a single release. All subsequent releases/deploys failed with Could not create SSL/TLS secure channel once more.
Simply adding it as a variable to the release definition did solve the problem. (To test it I have successfully deployed the same release to two environments, three times in a row.)
I found this solution here: https://github.com/Azure/azure-powershell/issues/13117#issuecomment-706665722
In my case I had accidentally mentioned https instead of http. My report server was http, without cert, but it used to redirect in browser even if I type https internally in our organization. But powershell needs the exact url. The version I used was powershell#2 and I invoked a powershell script file.

Azure Automation: VM shutdown runbook not working on new VM

I recently had to delete and re-install my VM due to an issue with the VM locking up. Now that the VM is back online, I noticed the shutdown automation is not working. It was working fine before I ran into the issue with the VM. Below is the PS script from the runbook, it returns the following error:
Correlation ID: 72fa8e58-89f1-4612-bc43-1b05876c2bff
Timestamp: 2015-08-25 06:04:14Z: The remote server returned an error: (401) Unauthorized.
At Shutdown:6 char:6
+
+ CategoryInfo : CloseError: (:) [Add-AzureAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.AddAzureAccount
8/24/2015 11:04:25 PM, Error: Get-azurevm : No default subscription has been designated.
Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.
At Shutdown:8 char:8
+
+ CategoryInfo : CloseError: (:) [Get-AzureVM], ApplicationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.GetAzureVMCommand
Any idea what I am missing to get this working with new VM? I have been wracking my brain for something with the credentials that would not include this new VM, but have come up empty handed.
workflow Shutdown
{
$Cred = Get-AutomationPSCredential -Name "auto"
Add-AzureAccount -Credential $Cred
$vms = Get-azurevm
foreach($VM in $VMS)
{
$VMName = $VM.Name
Stop-AzureVM -ServiceName $VM.ServiceName -Name $VM.Name -Force
Write-Output "Shutting down VM : $VMName "
}
}
I think you should also add the subscription name (select-azuresubscription in the error log) in the script you are using. There are quite some examples of doing this in various ways in the TechNet Script libraries like this one https://gallery.technet.microsoft.com/scriptcenter/Stop-Azure-VM-with-OrgID-41a79d91
I created a new user, granted them admin rights to the subscription, and updated the credential. That seemed to fix it, guessing it was something with the existing co-admin account not having access to the new VM.

Resources