# Copyright (c) Microsoft Corporation. # # This script will # 1. Examine Azcmagent configuration # 2. Get privileged properties and set them using partnerconfig # 3. Check if automatic upgrade is enabled # 4. Check if desired version is greater than existing agent version # 5. Check if automatic upgrade has already been attempted before # 6. Get the download link # 7. Execute install_azcmagent.ps1 to upgrade # # For more information: https://aka.ms/ArcAgentUpgrade #Requires -RunAsAdministrator $ErrorActionPreference="SilentlyContinue" Stop-Transcript | out-null $ErrorActionPreference = 'Stop' function Get-JSONObject { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $CmdString ) try { return $(Invoke-Expression $CmdString) | ConvertFrom-Json } catch { return "[$(Invoke-Expression $CmdString)]" | ConvertFrom-Json } } function Test-ProxyBypassEntry { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $EntryToFind ) $bypassList = ((Get-JSONObject -CmdString "azcmagent config list -j").LocalSettings | Where-Object { $_.key -eq "proxy.bypass" }).Value foreach ($entry in $bypassList) { if ($entry -is [string] -and $entry.Equals($EntryToFind, [System.StringComparison]::OrdinalIgnoreCase)) { return $true } } return $false } function Invoke-Failure { [CmdletBinding()] param( [Parameter(Mandatory=$true)] $Message, [Parameter(Mandatory=$true)] $ErrorCode, [Parameter(Mandatory=$false)] $Details ) $ex = new-object -TypeName System.Exception -ArgumentList @($Message) $ex.Data["Details"] = $details $ex.Data["ErrorCode"] = $errorcode throw $ex } function Send-Log { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Message, [Parameter(Mandatory = $true)] [string] $Code, [Parameter(Mandatory = $true)] [PSCustomObject] $Show ) $hisEndpoint = "https://gbl.his.arc.azure.com" if ($Show.cloud -eq "AzureUSGovernment") { $hisEndpoint = "https://gbl.his.arc.azure.us" } elseif ($Show.cloud -eq "AzureChinaCloud") { $hisEndpoint = "https://gbl.his.arc.azure.cn" } $logBody = @{subscriptionId=$Show.subscriptionId;resourceGroup=$Show.resourceGroup;resourceName=$Show.resourceName;tenantId=$Show.tenantId;location=$Show.location;correlationId=$Show.correlationId;operation="upgrading";messageType="$Code";message="$Message";} $proxy = (Get-JSONObject -CmdString "azcmagent config get proxy.url -j").Data $shouldBypassProxy = Test-ProxyBypassEntry -EntryToFind "arc" if ($proxy -and -not $shouldBypassProxy){ Invoke-WebRequest -UseBasicParsing -Proxy $proxy -Uri "$hisEndpoint/log" -Method "PUT" -Body ($logBody | ConvertTo-Json) -TimeoutSec 60 -ErrorAction SilentlyContinue | out-null } else{ Invoke-WebRequest -UseBasicParsing -Uri "$hisEndpoint/log" -Method "PUT" -Body ($logBody | ConvertTo-Json) -TimeoutSec 60 -ErrorAction SilentlyContinue | out-null } } function Set-SerialNumber { try { $serialNumberStatus = Get-JSONObject -CmdString "azcmagent partnerconfig get serialNumber --partner hcrp --json" if ($serialNumberStatus.status -eq "success") { # Serial number has been set return } } catch { Write-Error "Error getting serial number. Ensure azcmagent is updated: $_" return } $SerialNumber_None = "None" try { $serialNumber = Get-CimInstance -ClassName Win32_SystemEnclosure | Select-Object -ExpandProperty SerialNumber if (-not $serialNumber -or ($serialNumber -ieq $SerialNumber_None)) { $serialNumber = Get-CimInstance -ClassName Win32_BIOS | Select-Object -ExpandProperty SerialNumber if (-not $serialNumber -or ($serialNumber -ieq $SerialNumber_None)) { $serialNumber = (cmd.exe /c "wmic bios get serialnumber" | Select-String -Pattern "\S+" | ForEach-Object { $_.Line.Trim() })[1] } } } catch { Write-Error "Error retrieving serial number: $_" return } if (-not $serialNumber -or ($serialNumber -ieq $SerialNumber_None)) { return } azcmagent partnerconfig set serialNumber $serialNumber --partner hcrp } function Set-MachineProfile { azcmagent partnerconfig set machineprofile "all" --partner hcrp } try { # Ensure TLS 1.2 is accepted. Older PowerShell builds (sometimes) complain about the enum "Tls12" so we use the underlying value [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 # Ensure TLS 1.3 is accepted, if this .NET supports it (older versions don't) try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 12288 } catch {} try { $show = Get-JSONObject -CmdString "azcmagent show --json" } catch { Invoke-Failure -ErrorCode "AZCM0161" -Message "azcmagent show command failed: $_" } Set-SerialNumber Set-MachineProfile try { $enabled = azcmagent config get automaticupgrade.enabled if ($enabled -ne "true") { Send-Log "automaticupgrade.enabled not enabled" "AZCM0162" $show exit 0 } } catch { Invoke-Failure -ErrorCode "AZCM0163" -Message "unable to get automaticupgrade.enabled flag: $_" } #try { # $enabled = azcmagent config get automaticupgrade.blocklocally # if ($enabled -ne "false") { # Send-Log "automaticupgrade.blocklocally set to true" "AZCM0162" $show # exit 0 # } #} catch { # Invoke-Failure -ErrorCode "AZCM0163" -Message "unable to get automaticupgrade.blocklocally flag: $_" #} try { $desiredVersion = azcmagent config get automaticupgrade.desiredversion } catch { Invoke-Failure -ErrorCode "AZCM0164" -Message "unable to get automaticupgrade.desiredversion: $_" } $agentVersion = $show.agentVersion if ([System.Version]$agentVersion -gt [System.Version]$desiredVersion) { Send-Log "automaticupgrade.desiredversion $desiredVersion not greater than existing agent version $agentVersion" "AZCM0165" $show exit 0 } try { $lastattempt = azcmagent config get automaticupgrade.lastattempt.status } catch { Invoke-Failure -ErrorCode "AZCM0166" -Message "unable to get automaticupgrade.lastattempt.status field: $_" } if ($lastattempt -eq "success") { Send-Log "Last attempt was successful, skipping upgrade" "AZCM0167" $show exit 0 } if ($lastattempt -eq "failed") { $timestamp = Get-Date -UFormat %s -Millisecond 0 try { #$lastAttemptTimestamp = azcmagent config get automaticupgrade.lastattempt.timestamp #$lastAttemptTimestamp = [int]::Parse($lastAttemptTimestamp) #$timeSinceLastAttemptSec = $timestamp - $lastAttemptTimestamp #if($timeSinceLastAttemptSec -lt 60 * 60 * 24 * 3){ # 60 seconds/min * 60 min/hr * 24 hr/day * 3 days # Send-Log "Last attempt failed, skipping upgrade" "AZCM0168" $show # exit 0 #} } catch { Invoke-Failure -ErrorCode "AZCM0166" -Message "unable to check last attempt timestamp $_" } } try { $downloadlink = azcmagent config get automaticupgrade.downloadlink $proxy = (Get-JSONObject -CmdString "azcmagent config get proxy.url -j").Data $shouldBypassProxy = Test-ProxyBypassEntry -EntryToFind "arc" if ($proxy -and -not $shouldBypassProxy){ $response = Invoke-WebRequest -UseBasicParsing -Uri $downloadlink -Method Head -Proxy $proxy } else{ $response = Invoke-WebRequest -UseBasicParsing -Uri $downloadlink -Method Head } } catch { Invoke-Failure -ErrorCode "AZCM0169" -Message "unable to get or reach automaticupgrade.downloadlink: $_" } # do the upgrade using the on-boarding script $onboardingScriptPath = Join-Path -Path $env:ProgramFiles -ChildPath "AzureConnectedMachineAgent" | Join-Path -ChildPath "install_azcmagent.ps1" $outfilePath = Join-Path -Path $env:ProgramFiles -ChildPath "AzureConnectedMachineAgent" | Join-Path -ChildPath "install_output.txt" $autoupgradelog = Join-Path -Path $env:ProgramFiles -ChildPath "AzureConnectedMachineAgent" | Join-Path -ChildPath "autoupgrade.txt" $timestamp = Get-Date -UFormat %s -Millisecond 0 $proxy = (Get-JSONObject -CmdString "azcmagent config get proxy.url -j").Data if ($proxy){ & $onboardingScriptPath -AltDownload $downloadlink -OutFile $outfilePath -Proxy $proxy -ShouldBypassProxy $shouldBypassProxy *> $autoupgradelog } else{ & $onboardingScriptPath -AltDownload $downloadlink -OutFile $outfilePath *> $autoupgradelog } if ($LastExitCode -ne 0) { azcmagent config set automaticupgrade.lastattempt.status failed $outputJson = Get-Content $outfilePath | Out-String | ConvertFrom-Json if ($outputJson.error.details) { azcmagent config set automaticupgrade.lastattempt.message $outputJson.error.details } else { azcmagent config set automaticupgrade.lastattempt.message $outputJson.error.message } # no need to send logs to HIS since install_azcmagent.ps1 already sends logs if there is a failure } else { azcmagent config set automaticupgrade.lastattempt.status success azcmagent config set automaticupgrade.lastattempt.message "Success" Send-Log "Upgrade to $desiredVersion was successful" "AZCM0170" $show } azcmagent config set automaticupgrade.lastattempt.desiredversion $desiredVersion azcmagent config set automaticupgrade.lastattempt.timestamp $timestamp } catch { $code = $_.Exception.Data.ErrorCode if(!$code) { $code = "AZCM0150" } # default if we do not have some more specific error Write-Error $_ -ErrorAction Continue Send-Log $_.Exception $code $show exit 1 }