Packer.Images/scripts/Update-OvfConfiguration.ps1
djpbessems 8340b97a4d
Some checks failed
continuous-integration/drone/push Build is failing
Simplify code (different method for XML attributes)
2021-05-12 11:38:39 +02:00

394 lines
21 KiB
PowerShell

#Requires -Modules 'powershell-yaml'
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateScript({
If (Test-Path($_)) {
$True
} Else {
Throw "'$_' is not a valid filename (within working directory '$PWD'), or access denied; aborting."
}
})]
[string]$OVFFile,
[hashtable]$Parameter
)
$GetContentSplat = @{
Path = "$($PSScriptRoot)\$($MyInvocation.MyCommand)".Replace('.ps1', ".yml")
Raw = $True
}
$RawContent = Get-Content @GetContentSplat
$ConvertFromYamlSplat = @{
Yaml = $RawContent
AllDocuments = $True
}
$YamlDocuments = ConvertFrom-Yaml @ConvertFromYamlSplat
# Check if the respective .yml file declared substitutions which need to be parsed
If (($YamlDocuments.Count -gt 1) -and $YamlDocuments[-1].Variables) {
ForEach ($Pattern in $YamlDocuments[-1].Variables) {
$RawContent = $RawContent -replace "\{\{ ($($Pattern.Name)) \}\}", [string](Invoke-Expression -Command $Pattern.Expression)
}
# Perform conversion to Yaml again, now with parsed file contents
$ConvertFromYamlSplat = @{
Yaml = $RawContent
AllDocuments = $True
}
$YamlDocuments = ConvertFrom-Yaml @ConvertFromYamlSplat
$OVFConfig = $YamlDocuments[0..($YamlDocuments.Count - 2)]
}
Else {
$OVFConfig = $YamlDocuments
}
$SourceFile = Get-Item -Path $OVFFile
$GetContentSplat = @{
Path = $SourceFile.FullName
}
$XML = [xml](Get-Content @GetContentSplat)
$NS = [System.Xml.XmlNamespaceManager]$XML.NameTable
[void]$NS.AddNamespace('ns', $XML.DocumentElement.xmlns)
[void]$NS.AddNamespace('ovf', $XML.DocumentElement.ovf)
[void]$NS.AddNamespace('rasd', $XML.DocumentElement.rasd)
# Create copy of default resourceType=17 (=Harddisk) node
$XMLDiskTemplate = $XML.SelectSingleNode("//ns:VirtualHardwareSection/ns:Item/rasd:ResourceType[.='17']", $NS).ParentNode.CloneNode($True)
ForEach ($Disk in $OVFConfig.DynamicDisks) {
# Determine next free available diskId
$XMLDisks = $XML.SelectNodes("//ns:DiskSection/ns:Disk[contains(@ovf:diskId,'vmdisk')]", $NS)
$DiskId = $XMLDisks.Count + 1
While ($XMLDisks.DiskId -contains "vmdisk$($DiskId)") {
$DiskId++
}
$XMLDisk = $XML.CreateElement('Disk', $XML.DocumentElement.xmlns)
# $XMLDiskAttrUnits = $XML.CreateAttribute('capacityAllocationUnits', $XML.DocumentElement.ovf)
Switch ($Disk.UnitSize) {
'KB' {
$Powers = 10
}
'MB' {
$Powers = 20
}
'GB' {
$Powers = 30
}
'TB' {
$Powers = 40
}
'PB' {
$Powers = 50
}
default {
# Invalid UnitSize; skipping modification of existing disk
Continue
}
}
# $XMLDiskAttrUnits.Value = "byte * 2^$($Powers)"
[void]$XMLExtraConfig.SetAttribute('capacityAllocationUnits', $NS.LookupNamespace('ovf'), "byte * 2^$($Powers)")
# $XMLDiskAttrFormat = $XML.CreateAttribute('format', $XML.DocumentElement.ovf)
# $XMLDiskAttrFormat.Value = 'http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized'
[void]$XMLExtraConfig.SetAttribute('format', $NS.LookupNamespace('ovf'), 'http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized')
# $XMLDiskId = $XML.CreateAttribute('diskId', $XML.DocumentElement.ovf)
# $XMLDiskId.Value = "vmdisk$($DiskId)"
[void]$XMLExtraConfig.SetAttribute('diskId', $NS.LookupNamespace('ovf'), "vmdisk$($DiskId)")
# $XMLDiskAttrCapacity = $XML.CreateAttribute('capacity', $XML.DocumentElement.ovf)
# $XMLDiskAttrCapacity.Value = '${{vmconfig.disksize.{0}}}' -f $DiskId
[void]$XMLExtraConfig.SetAttribute('capacity', $NS.LookupNamespace('ovf'), '${{vmconfig.disksize.{0}}}' -f $DiskId)
# $XMLDiskAttrPopulated = $XML.CreateAttribute('populatedSize', $XML.DocumentElement.ovf)
# $XMLDiskAttrPopulated.Value = 0
[void]$XMLExtraConfig.SetAttribute('populatedSize', $NS.LookupNamespace('ovf'), 0)
# [void]$XMLDisk.Attributes.Append($XMLDiskAttrUnits)
# [void]$XMLDisk.Attributes.Append($XMLDiskAttrFormat)
# [void]$XMLDisk.Attributes.Append($XMLDiskId)
# [void]$XMLDisk.Attributes.Append($XMLDiskAttrCapacity)
# [void]$XMLDisk.Attributes.Append($XMLDiskAttrPopulated)
[void]$XML.SelectSingleNode('//ns:DiskSection', $NS).AppendChild($XMLDisk)
# Add new resourceType nodes
$XMLDiskItem = $XMLDiskTemplate.CloneNode($True)
$XMLDiskItem.SelectSingleNode('rasd:AddressOnParent', $NS).InnerText = ($DiskId - 1)
$XMLDiskItem.SelectSingleNode('rasd:ElementName', $NS).InnerText = "Hard Disk $($DiskId)"
$XMLDiskItem.SelectSingleNode('rasd:HostResource', $NS).InnerText = "ovf:/disk/vmdisk$($DiskId)"
# Determine next free available InstanceID
$InstanceIDs = $XML.SelectNodes('//ns:VirtualHardwareSection/ns:Item/rasd:InstanceID', $NS)
$InstanceID = 1
While ($InstanceIDs.InnerText -contains $InstanceID) {
$InstanceID++
}
$XMLDiskItem.SelectSingleNode('rasd:InstanceID', $NS).InnerText = $InstanceID
$XML.SelectSingleNode('//ns:VirtualHardwareSection', $NS).AppendChild($XMLDiskItem)
$OVFConfig.PropertyCategories[0].ProductProperties += @{
Key = "vmconfig.disksize.$($DiskId)"
Type = If ([boolean]$Disk.Constraints.Minimum -or [boolean]$Disk.Constraints.Maximum) {
"Int($($Disk.Constraints.Minimum)..$($Disk.Constraints.Maximum))"
}
Else {
'Int'
}
Label = "Disk $($DiskId) size*"
Description = "$($Disk.Description) (in $($Disk.UnitSize))".Trim()
DefaultValue = "$($Disk.Constraints.Minimum)"
Configurations = '*'
UserConfigurable = 'true'
}
}
Write-Host "Inserted $($OVFConfig.DynamicDisks.Count) new node(s) into 'DiskSection' and 'VirtualHardwareSection' respectively"
If ($OVFConfig.DeploymentConfigurations.Count -gt 0) {
$XMLSection = $XML.CreateElement('DeploymentOptionSection', $XML.DocumentElement.xmlns)
$XMLSectionInfo = $XML.CreateElement('Info', $XML.DocumentElement.xmlns)
$XMLSectionInfo.InnerText = 'Deployment Type'
[void]$XMLSection.AppendChild($XMLSectionInfo)
ForEach ($Configuration in $OVFConfig.DeploymentConfigurations) {
$XMLConfig = $XML.CreateElement('Configuration', $XML.DocumentElement.xmlns)
# $XMLConfigAttrId = $XML.CreateAttribute('id', $XML.DocumentElement.ovf)
# $XMLConfigAttrId.Value = $Configuration.Id
[void]$XMLExtraConfig.SetAttribute('id', $NS.LookupNamespace('ovf'), $Configuration.Id)
$XMLConfigLabel = $XML.CreateElement('Label', $XML.DocumentElement.xmlns)
$XMLConfigLabel.InnerText = $Configuration.Label
$XMLConfigDescription = $XML.CreateElement('Description', $XML.DocumentElement.xmlns)
$XMLConfigDescription.InnerText = $Configuration.Description
# [void]$XMLConfig.Attributes.Append($XMLConfigAttrId)
[void]$XMLConfig.AppendChild($XMLConfigLabel)
[void]$XMLConfig.AppendChild($XMLConfigDescription)
[void]$XMLSection.AppendChild($XMLConfig)
}
[void]$XML.SelectSingleNode('//ns:Envelope', $NS).InsertAfter($XMLSection, $XML.SelectSingleNode('//ns:NetworkSection', $NS))
Write-Host "Inserted 'DeploymentOptionSection' with $($Configuration.Count) nodes"
If ($OVFConfig.DeploymentConfigurations.Count -eq $OVFConfig.DeploymentConfigurations.Size.Count) {
# Create copies of default resourceType nodes
$XMLCPUTemplate = $XML.SelectSingleNode("//ns:VirtualHardwareSection/ns:Item/rasd:ResourceType[.='3']", $NS).ParentNode.CloneNode($True)
$XMLMemoryTemplate = $XML.SelectSingleNode("//ns:VirtualHardwareSection/ns:Item/rasd:ResourceType[.='4']", $NS).ParentNode.CloneNode($True)
# Delete default resourceType nodes
ForEach ($Node in $XML.SelectNodes("//ns:VirtualHardwareSection/ns:Item/rasd:ResourceType[.='3' or .='4']", $NS).ParentNode) {
$Node.ParentNode.RemoveChild($Node)
}
# Add updated resourceType nodes
ForEach ($Configuration in $OVFConfig.DeploymentConfigurations) {
$XMLCPU = $XMLCPUTemplate.CloneNode($True)
[void]$XMLCPU.SetAttribute('configuration', $NS.LookupNamespace('ovf'), $Configuration.Id)
$XMLCPU.SelectSingleNode('rasd:ElementName', $NS).InnerText = '{0} virtual CPU(s)' -f $Configuration.Size.CPU
$XMLCPU.SelectSingleNode('rasd:VirtualQuantity', $NS).InnerText = $Configuration.Size.CPU
$XMLMemory = $XMLMemoryTemplate.CloneNode($True)
[void]$XMLMemory.SetAttribute('configuration', $NS.LookupNamespace('ovf'), $Configuration.Id)
$XMLMemory.SelectSingleNode('rasd:ElementName', $NS).InnerText = '{0}MB of memory' -f $Configuration.Size.Memory
$XMLMemory.SelectSingleNode('rasd:VirtualQuantity', $NS).InnerText = $Configuration.Size.Memory
$XML.SelectSingleNode('//ns:VirtualHardwareSection', $NS).AppendChild($XMLCPU)
$XML.SelectSingleNode('//ns:VirtualHardwareSection', $NS).AppendChild($XMLMemory)
}
}
}
# $XMLAttrTransport = $XML.CreateAttribute('transport', $XML.DocumentElement.ovf)
# $XMLAttrTransport.Value = 'com.vmware.guestInfo'
# [void]$XML.SelectSingleNode('//ns:VirtualHardwareSection', $NS).Attributes.Append($XMLAttrTransport)
[void]$XML.SelectSingleNode('//ns:VirtualHardwareSection', $NS).SetAttribute('transport', $NS.LookupNamespace('ovf'), 'com.vmware.guestInfo')
ForEach ($ExtraConfig in $OVFConfig.AdvancedOptions) {
$XMLExtraConfig = $XML.CreateElement('vmw:ExtraConfig', $XML.DocumentElement.vmw)
# $XMLExtraConfigAttrRequired = $XML.CreateAttribute('required', $XML.DocumentElement.ovf)
# $XMLExtraConfigAttrRequired.Value = "$([boolean]$ExtraConfig.Required)".ToLower()
# $XMLExtraConfigAttrKey = $XML.CreateAttribute('key', $XML.DocumentElement.vmw)
# $XMLExtraConfigAttrKey.Value = $ExtraConfig.Key
# $XMLExtraConfigAttrValue = $XML.CreateAttribute('value', $XML.DocumentElement.vmw)
# $XMLExtraConfigAttrValue.Value = $ExtraConfig.Value
# [void]$XMLExtraConfig.Attributes.Append($XMLExtraConfigAttrRequired)
[void]$XMLExtraConfig.SetAttribute('required', $NS.LookupNamespace('ovf'), "$([boolean]$ExtraConfig.Required)".ToLower())
# [void]$XMLExtraConfig.Attributes.Append($XMLExtraConfigAttrKey)
[void]$XMLExtraConfig.SetAttribute('key', $NS.LookupNamespace('vmw'), $ExtraConfig.Key)
# [void]$XMLExtraConfig.Attributes.Append($XMLExtraConfigAttrValue)
[void]$XMLExtraConfig.SetAttribute('value', $NS.LookupNamespace('vmw'), $ExtraConfig.Value)
[void]$XML.SelectSingleNode('//ns:VirtualHardwareSection', $NS).AppendChild($XMLExtraConfig)
}
Write-Host "Added $($OVFConfig.AdvancedOptions.Count) 'vmw:ExtraConfig' nodes"
$XMLProductSection = $XML.SelectSingleNode('//ns:ProductSection', $NS)
If ($XMLProductSection -eq $Null) {
$XMLProductSection = $XML.CreateElement('ProductSection', $XML.DocumentElement.xmlns)
[void]$XML.SelectSingleNode('//ns:VirtualSystem', $NS).AppendChild($XMLProductSection)
Write-Host "Inserted 'ProductSection'"
} Else {
ForEach ($Child in $XMLProductSection.SelectNodes('//ns:ProductSection/child::*', $NS)) {
[void]$Child.ParentNode.RemoveChild($Child)
}
Write-Host "Destroyed pre-existing children in 'ProductSection'"
}
$XMLProductSectionInfo = $XML.CreateElement('Info', $XML.DocumentElement.xmlns)
$XMLProductSectionInfo.InnerText = 'Information about the installed software'
[void]$XMLProductSection.AppendChild($XMLProductSectionInfo)
Write-Host "Inserted new 'Info' into 'ProductSection'"
ForEach ($Category in $OVFConfig.PropertyCategories) {
If ($Category.Name -ne '') {
$XMLCategory = $XML.CreateElement('Category', $XML.DocumentElement.xmlns)
$XMLCategory.InnerText = $Category.Name
[void]$XMLProductSection.AppendChild($XMLCategory)
Write-Host "Inserted new 'Category' into 'ProductSection'"
}
ForEach ($Property in $Category.ProductProperties) {
$XMLProperty = $XML.CreateElement('Property', $XML.DocumentElement.xmlns)
# $XMLPropertyAttrKey = $XML.CreateAttribute('key', $XML.DocumentElement.ovf)
# $XMLPropertyAttrKey.Value = $Property.Key
$XMLProperty.SetAttribute('key', $NS.LookupNamespace('ovf'), $Property.Key)
# $XMLPropertyAttrType = $XML.CreateAttribute('type', $XML.DocumentElement.ovf)
Switch -regex ($Property.Type) {
'^boolean' {
# $XMLPropertyAttrType.Value = 'boolean'
$XMLProperty.SetAttribute('type', $NS.LookupNamespace('ovf'), 'boolean')
}
'^int' {
# $XMLPropertyAttrType.Value = 'uint16'
$XMLProperty.SetAttribute('type', $NS.LookupNamespace('ovf'), 'uint16')
$Qualifiers = @()
If ($Property.Type -match '^int\((\d*)\.\.(\d*)\)') {
If ($Matches[1]) {
$Qualifiers += "MinValue($($Matches[1]))"
}
If ($Matches[2]) {
$Qualifiers += "MaxValue($($Matches[2]))"
}
# $XMLPropertyAttrQualifiers = $XML.CreateAttribute('qualifiers', $XML.DocumentElement.ovf)
# $XMLPropertyAttrQualifiers.Value = $Qualifiers -join ' '
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrQualifiers)
$XMLProperty.SetAttribute('qualifiers', $NS.LookupNamespace('ovf'), $Qualifiers -join ' ')
}
}
'^ip' {
# $XMLPropertyAttrType.Value = 'string'
$XMLProperty.SetAttribute('type', $NS.LookupNamespace('ovf'), 'string')
# $XMLPropertyAttrQualifiers = $XML.CreateAttribute('qualifiers', $XML.DocumentElement.vmw)
# $XMLPropertyAttrQualifiers.Value = 'Ip'
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrQualifiers)
$XMLProperty.SetAttribute('qualifiers', $NS.LookupNamespace('vmw'), 'Ip')
}
'^password' {
# $XMLPropertyAttrType.Value = 'string'
$XMLProperty.SetAttribute('type', $NS.LookupNamespace('ovf'), 'string')
# $XMLPropertyAttrPassword = $XML.CreateAttribute('password', $XML.DocumentElement.ovf)
# $XMLPropertyAttrPassword.Value = 'true'
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrPassword)
$XMLProperty.SetAttribute('password', $NS.LookupNamespace('ovf'), 'true')
$Qualifiers = @()
If ($Property.Type -match '^password\((\d*)\.\.(\d*)\)') {
If ($Matches[1]) {
$Qualifiers += "MinLen($($Matches[1]))"
}
If ($Matches[2]) {
$Qualifiers += "MaxLen($($Matches[2]))"
}
# $XMLPropertyAttrQualifiers = $XML.CreateAttribute('qualifiers', $XML.DocumentElement.ovf)
# $XMLPropertyAttrQualifiers.Value = $Qualifiers -join ' '
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrQualifiers)
$XMLProperty.SetAttribute('qualifiers', $NS.LookupNamespace('ovf'), $Qualifiers -join ' ')
}
}
'^string' {
# $XMLPropertyAttrType.Value = 'string'
$XMLProperty.SetAttribute('type', $NS.LookupNamespace('ovf'), 'string')
$Qualifiers = @()
If ($Property.Type -match '^string\((\d*)\.\.(\d*)\)') {
If ($Matches[1]) {
$Qualifiers += "MinLen($($Matches[1]))"
}
If ($Matches[2]) {
$Qualifiers += "MaxLen($($Matches[2]))"
}
# $XMLPropertyAttrQualifiers = $XML.CreateAttribute('qualifiers', $XML.DocumentElement.ovf)
# $XMLPropertyAttrQualifiers.Value = $Qualifiers -join ' '
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrQualifiers)
$XMLProperty.SetAttribute('qualifiers', $NS.LookupNamespace('ovf'), $Qualifiers -join ' ')
} ElseIf ($Property.Type -match '^string\[(.*)\]') {
# $XMLPropertyAttrQualifiers = $XML.CreateAttribute('qualifiers', $XML.DocumentElement.ovf)
# $XMLPropertyAttrQualifiers.Value = "ValueMap{$($Matches[1] -replace '","', '", "')}"
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrQualifiers)
$XMLProperty.SetAttribute('qualifiers', $NS.LookupNamespace('ovf'), "ValueMap{$($Matches[1] -replace '","', '", "')}")
}
}
}
# $XMLPropertyAttrUserConfigurable = $XML.CreateAttribute('userConfigurable', $XML.DocumentElement.ovf)
# $XMLPropertyAttrUserConfigurable.Value = "$([boolean]$Property.UserConfigurable)".ToLower()
$XMLProperty.SetAttribute('userConfigurable', $NS.LookupNamespace('ovf'), "$([boolean]$Property.UserConfigurable)".ToLower())
# $XMLPropertyAttrValue = $XML.CreateAttribute('value', $XML.DocumentElement.ovf)
If ($Property.Type -eq 'boolean') {
# $XMLPropertyAttrValue.Value = "$([boolean]$Property.DefaultValue)".ToLower()
$XMLProperty.SetAttribute('value', $NS.LookupNamespace('ovf'), "$([boolean]$Property.DefaultValue)".ToLower())
} Else {
# $XMLPropertyAttrValue.Value = $Property.DefaultValue
$XMLProperty.SetAttribute('value', $NS.LookupNamespace('ovf'), $Property.DefaultValue)
}
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrKey)
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrType)
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrUserConfigurable)
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrValue)
If ($Property.Label) {
$XMLPropertyLabel = $XML.CreateElement('Label', $XML.DocumentElement.xmlns)
$XMLPropertyLabel.InnerText = $Property.Label
[void]$XMLProperty.AppendChild($XMLPropertyLabel)
}
If ($Property.Description) {
$XMLPropertyDescription = $XML.CreateElement('Description', $XML.DocumentElement.xmlns)
$XMLPropertyDescription.InnerText = $Property.Description
[void]$XMLProperty.AppendChild($XMLPropertyDescription)
}
If (($Property.Configurations.Count -eq 1) -and ($Property.Configurations -eq '*')) {
# $XMLPropertyAttrConfiguration = $XML.CreateAttribute('configuration', $XML.DocumentElement.ovf)
# $XMLPropertyAttrConfiguration.Value = $OVFConfig.DeploymentConfigurations.Id -join ' '
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrConfiguration)
$XMLProperty.SetAttribute('configuration', $NS.LookupNamespace('ovf'), $OVFConfig.DeploymentConfigurations.Id -join ' ')
} ElseIf ($Property.Configurations.Count -gt 0) {
# $XMLPropertyAttrConfiguration = $XML.CreateAttribute('configuration', $XML.DocumentElement.ovf)
# $XMLPropertyAttrConfiguration.Value = $Property.Configurations -join ' '
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrConfiguration)
$XMLProperty.SetAttribute('configuration', $NS.LookupNamespace('ovf'), $Property.Configurations -join ' ')
}
If ($Property.Value.Count -eq 1) {
# $XMLPropertyAttrValue = $XML.CreateAttribute('value', $XML.DocumentElement.ovf)
# $XMLPropertyAttrValue.Value = $Property.Value
# [void]$XMLProperty.Attributes.Append($XMLPropertyAttrValue)
$XMLProperty.SetAttribute('value', $NS.LookupNamespace('ovf'), $Property.Value)
} ElseIf ($Property.Value.Count -gt 1) {
ForEach ($Value in $Property.Value) {
$XMLValue = $XML.CreateElement('Value', $XML.DocumentElement.xmlns)
# $XMLValueAttrValue = $XML.CreateAttribute('value', $XML.DocumentElement.ovf)
# $XMLValueAttrValue.Value = $Value
$XMLProperty.SetAttribute('value', $NS.LookupNamespace('ovf'), $Value)
# $XMLValueAttrConfiguration = $XML.CreateAttribute('configuration', $XML.DocumentElement.ovf)
# $XMLValueAttrConfiguration.Value = $Value
$XMLProperty.SetAttribute('configuration', $NS.LookupNamespace('ovf'), $Value)
# [void]$XMLValue.Attributes.Append($XMLValueAttrValue)
# [void]$XMLValue.Attributes.Append($XMLValueAttrConfiguration)
[void]$XMLProperty.AppendChild($XMLValue)
}
}
[void]$XMLProductSection.AppendChild($XMLProperty)
}
Write-Host "Inserted $($Category.ProductProperties.Count) new node(s) into 'ProductSection'"
}
$XML.Save($SourceFile.FullName)