Azure DevOps Powershell 스크립트가 SSL / TLS 보안 채널을 만들 수 없습니다.
문제 : DevOps Pipeline의 'Azure Powershell'작업에서 Get-AzureDeployment (Get-AzureService)
명령을 호출하면 ' 요청이 중단되었습니다. SSL / TLS 보안 채널을 만들 수 없습니다. '
소개:
- Azure DevOps를 사용하여 Azure에 Azure 클라우드 서비스 (클래식)를 배포합니다.
- 'Azure Powershell'작업이 계속 작동했지만 아무것도 변경하지 않고 작동이 중지되었습니다.
- 또한 인증서 (DevOps에서 사용)를 내 PC (Import-AzurePublishSettingsFile)로 가져오고 동일한 powershell 스크립트를 실행하려고 시도했으며 everytnig가 제대로 작동하므로 DevOps에서 문제가 발생할 것으로 예상됩니다.
DevOps 연결 :
- Azure에 연결하기 위해 Azure DevOps에서 '서비스 연결'을 만들었습니다.
- 서비스 연결은 'Azure 클래식'유형입니다 ( 'Azure Resource Manager'는 '클라우드 서비스 클래식'용이 아니기 때문).
- 'Azure Classic 서비스 연결'의 인증 방법은 '인증서 기반'입니다.
- Azure 구독에 '게시 설정 파일'에서 생성 한 인증서를 사용했습니다. Azure에서 My-subscription-> Management 인증서에 인증서를 배치했습니다 (만료 날짜는 2021 년 중반 임).
- 이 서비스 연결을 사용하여 앱 (클라우드 서비스 클래식)을 Azure 에 아무 문제없이 (DevOps 작업 'Azure Cloud Service 배포'에 의해) 배포 하지만 'Azure Powershell'작업 만 실패 합니다.
이 모든 것이 3 개월 동안 작동하다가 어떤 이유로 든 작동을 중단했습니다. 이상한 점은 내가 DevOps를 사용하여 무엇이 잘못되었는지 알아 내려고 할 때 작업이 성공적으로 실행되었지만 다시 시도했을 때 오류가 다시 발생했다는 것입니다.
성공한 통화와 실패한 통화의 로그가 모두 있습니다. 2506 줄의 로그는 동일하며이 줄 이후에 변경됩니다.
두 가지 전체 로그를 모두 보낼 수 있지만 여기에 너무 긴 로그를 배치하고 싶지 않습니다.
성공적인 시도 :
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
실패한 호출에서 로그 :
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]
두 로그에서 Powershell에 Azure 계정을 추가하기 위해 다음을 찾을 수도 있습니다.
##[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
(일부 문자열을 X로 대체했습니다)
YAML에는 Powershell 작업이 있습니다.
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
로컬 PC (동일한 인증서 사용)에서 작동하지만 DevOps에서는 실패하는 슬롯을 교체하기위한 Powershell 스크립트 :
[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)
}
나와 같은 경험이있는 사람이 있습니까? 어디에 문제가 있습니까?
# 업데이트
스크립트 시작 부분에이 보안 프로토콜 설정을 추가하려고했지만 동일한 오류가 발생했습니다.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
답변
이것은 Microsoft 빌드 에이전트의 문제로 보이지만 각 Azure Powershell 작업의 시작 부분에 다음 코드를 추가하면 문제를 파악할 때까지이 문제가 해결 된 것으로 보입니다.
$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
작동하는 몇 가지 해결 방법이 있습니다.
해결 방법 1
- Azure Powershell 작업 버전 5 사용
- "Azure Resource Manager 연결"을 선택합니다.
- ASM 모듈 명령 을 Az 명령으로 변경
해결 방법 2
- Azure Powershell 작업 버전 3 사용
- 클래식 연결
- Azure Powershell 버전을 4.2.1로 다운 그레이드
해결 방법 3 (개인 에이전트 용)
- CurrentUser \ My store에서 자체 서명 된 인증서를 만듭니다. 여기에서 자체 서명 된 인증서를 만드는 방법에 대한 세부 정보를 찾을 수 있습니다.https://docs.microsoft.com/en-us/azure/cloud-services/cloud-services-certs-create
- 인증서의 공개 키를 DER로 인코딩 된 CER 파일로 내 보냅니다 (mmc 또는 다른 인증서 도구를 사용할 수 있음).
- 포털을 통해 .Cer 파일을 관리 인증서로 업로드합니다. https://docs.microsoft.com/en-us/previous-versions/azure/azure-api-management-certs
- Set-AzureSubscription을 사용하여 인증 :
PS C : \> Clear-AzureProfile PS C : \> $cert = Get-Item Cert:\CurrentUser\My\ PS C:\ > Set-AzureSubscription -SubscriptionName "" -SubscriptionId -Certificate $인증서 PS C : \> Select-AzureSubscription -SubscriptionId
해결 방법 4
각 Azure Powershell 작업에 아래 스크립트 추가
$p = (Get-Variable Endpoint -ValueOnly).Auth.Parameters.certificate $바이트 = [변환] :: FromBase64String ($p) [IO.File]::WriteAllBytes("C:\cert.pfx",$바이트) Import-PfxCertificate -FilePath C : \ cert.pfx -CertStoreLocation cert : \ CurrentUser \ My . . 실제 스크립트 . . # 저장소에서 인증서 제거 $thumb = (Get-PfxData -FilePath "C:\cert.pfx").EndEntityCertificates.Thumbprint Remove-Item -Path cert:\CurrentUser\My\$thumb -recurse -Force
우리는 같은 문제가있었습니다. windows-2019에이전트 에서만 나타 났 으며 vs2017-win2016. 따라서 에이전트 유형을 변경하여 문제를 해결할 수 있지만 더 나은 해결 방법은 5.1.1대신 특정 Powershell 버전을 사용하는 것입니다 latest. 이 오류를 일으키는 latest최근 증가한 것으로 보입니다 5.3.0.
동일한 문제가 발생하여이 모든 작업을 시도했습니다. Initialize-Azure 부분 다음에 추가 한 경우에만 작동했습니다. "Set-AzureSubscription -SubscriptionId [내 구독 ID] -CurrentStorageAccountName [스토리지 이름]"
이 문제는 .NET 9 월 업데이트에 도입 된 동작 변경으로 인해 발생합니다. 다음 코드는 환경 변수를 통해 키의 암시 적 저장소 (이전 .Net 4.x 동작)를 복원합니다.
Set-Item env:\COMPLUS_CngImplicitPersistKeySet 1
참고 : 이후 가져 오기에서 이전 인증서와 키를 덮어 쓰지 않으므로 새 게시 설정 파일을 만들어야합니다.
Az Powershell 버전을 4.2.1로 다운 그레이드하는 것은 AzurePowerShell @ 3 작업을 사용하여 작동합니다.
제 경우에는 Get-AzureServiceRemoteDesktopExtension온-프레미스 Team Foundation Server 2017에서 "인라인 Azure Powershell 실행"작업 의 명령 에이 문제가있었습니다 .
여기에 제안 된 @ damien-caro 줄을 추가해 보았습니다 ...
Set-Item env:\COMPLUS_CngImplicitPersistKeySet 1
... 내 스크립트에 있지만 단일 릴리스에 대한 문제 만 해결되었습니다. 모든 후속 릴리스 / 배포가 한 Could not create SSL/TLS secure channel번 더 실패했습니다 .
릴리스 정의에 변수로 추가하기 만해도 문제가 해결되었습니다. (테스트를 위해 동일한 릴리스를 두 환경에 세 번 연속으로 성공적으로 배포했습니다.)
여기에서이 솔루션을 찾았습니다. https://github.com/Azure/azure-powershell/issues/13117#issuecomment-706665722