ps/Modules/Alkami.DevOps.Inventory/Public/Sync-PlatformElementInventory.ps1
2023-05-30 22:51:22 -07:00

85 lines
3.2 KiB
PowerShell

function Sync-PlatformElementInventory {
<#
.SYNOPSIS
Fully synchronizes the element inventory of an Environment to BoRG. The final BoRG contents will
match the environment contents. Useful for populating BoRG with the element list of a new environment or
correcting major deviations.
WARNING: This function persists ALL discovered elements in an environment, regardless of tier. Elements
installed on an incorrect tier can result in a failed MDV during deployments.
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[string[]]$Servers,
[Parameter(Mandatory = $true)]
[string]$EnvironmentName,
[Parameter(Mandatory = $true)]
[string]$BorgUri,
[Parameter(Mandatory = $true)]
[string]$ApiKey
)
Write-Host "Starting BoRG full sync for $EnvironmentName..."
#Pull current BoRG Inventory
try {
Write-Host "Retrieving BoRG platform element inventory for $EnvironmentName."
$borgInventory = (Get-PlatformElementInventory -BorgUri $BorgUri -EnvironmentName $EnvironmentName)
} catch {
Write-Error "An error occurred Retrieving BoRG inventory: $($_.Exception.Message)"
}
#Pull machine inventory
Write-Host "Retrieving machine inventory for $($Servers -join ',')."
$machineInventory = (Get-MachineInventory -ComputerNames $Servers -Filter Chocolatey,ServiceFabric)
#Compare contents of Machines against BoRG and build add/remove collections
$borgElementsToAdd = @{}
$borgElementsToRemove = @{}
foreach ($key in $machineInventory.Keys) {
#Get element list from inventory
$machineTier = $key.SubString(0,3).ToLower()
if ($machineTier -eq "fab") {
$machineElements = $machineInventory.$key.ConfigData.ServiceFabric.Packages
} else {
$machineElements = $machineInventory.$key.ConfigData.Chocolatey.Packages
}
Write-Host "Determining elements to add/update for $key."
foreach ($element in $machineElements.Values) {
if ($element.SourceName -match "Alkami|SDK" -and $element.Name -notmatch "PowerShell" -and !$borgElementsToAdd.ContainsKey($element.Name)) {
$borgElementsToAdd[$element.Name] = $element
}
}
}
Write-Host "Determining elements to remove from BoRG."
foreach ($element in $borgInventory) {
if (!$borgElementsToAdd.ContainsKey($element.Name)) {
$borgElementsToRemove[$element.Name] = $element
}
}
#Update BoRG
Write-Host "Updating BoRG [$BorgUri] Inventory."
try {
Update-PlatformElementInventory `
-ElementsToAdd @($borgElementsToAdd.Values) `
-ElementsToRemove @($borgElementsToRemove.Values) `
-EnvironmentTypeName $EnvironmentName `
-PlatformVersionName "Unspecified" `
-ElementTierName "Unknown" `
-BorgUri $BorgUri `
-ApiKey $ApiKey
} catch {
Write-Error "An exception occurred while updating BoRG. Error: $($_.Exception.Message)"
}
Write-Host "BoRG full sync for $EnvironmentName completed successfully."
}