From 2c75bd9e611265b45b1716463cdfa1c71b32eac2 Mon Sep 17 00:00:00 2001 From: "Prince Nagar (BEYONDSOFT CONSULTING INC)" Date: Wed, 25 Nov 2026 12:06:12 +0530 Subject: [PATCH 1/6] feat(deploy-accelerator): support renamed architecture definition files Deploy-Accelerator copies config/lib on top of the starter lib, so a renamed architecture file sat next to the starter's alz_custom file while the bootstrap kept reading the default terraform_architecture_file_path. The bootstrap then built the intermediate root management group from the wrong file, or the library held two architectures with the same name. When terraform_architecture_file_path is not supplied, New-Bootstrap now looks for *.alz_architecture_definition.{json,yaml,yml} files in the starter additional files whose name matches management_group_settings.architecture_name (or the starter default file's name). A single match outside the default path is passed to the bootstrap, and the starter default file is removed when it declares the same architecture. More than one match stops with an error. actions_bootstrap.ps1 installs powershell-yaml so the new tests can parse YAML architecture files on the CI runner. Refs Azure/Azure-Landing-Zones#4068 --- actions_bootstrap.ps1 | 5 + .../New-Bootstrap.ps1 | 33 +++++ .../Resolve-TerraformArchitectureFile.ps1 | 93 +++++++++++++ .../Unit/Private/New-Bootstrap.Tests.ps1 | 129 ++++++++++++++++++ ...esolve-TerraformArchitectureFile.Tests.ps1 | 119 ++++++++++++++++ 5 files changed, 379 insertions(+) create mode 100644 src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 create mode 100644 src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 create mode 100644 src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 diff --git a/actions_bootstrap.ps1 b/actions_bootstrap.ps1 index 71665a48..0218488b 100644 --- a/actions_bootstrap.ps1 +++ b/actions_bootstrap.ps1 @@ -29,6 +29,11 @@ $null = $modulesToInstall.Add(([PSCustomObject]@{ ModuleName = 'platyPS' ModuleVersion = '0.12.0' })) +# https://github.com/cloudbase/powershell-yaml +$null = $modulesToInstall.Add(([PSCustomObject]@{ + ModuleName = 'powershell-yaml' + ModuleVersion = '0.4.12' + })) 'Installing PowerShell Modules' foreach ($module in $modulesToInstall) { diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 index 54cd4381..71fad7f6 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 @@ -181,6 +181,34 @@ function New-Bootstrap { } } + $architectureFileToRemove = $null + $architectureFilePathInputName = "terraform_architecture_file_path" + if ($iac -eq "terraform" -and $hasStarter -and + $bootstrapParameters.PSObject.Properties.Name -contains $architectureFilePathInputName -and + $inputConfig.PSObject.Properties.Name -notcontains $architectureFilePathInputName -and + $null -eq [Environment]::GetEnvironmentVariable("TF_VAR_$architectureFilePathInputName")) { + + $architectureName = "" + if ($inputConfig.PSObject.Properties.Name -contains "management_group_settings" -and $null -ne $inputConfig.management_group_settings.Value.architecture_name) { + $architectureName = $inputConfig.management_group_settings.Value.architecture_name + } + + $architectureFile = Resolve-TerraformArchitectureFile ` + -starterModulePath $starterRootModuleFolderPath ` + -starterAdditionalFiles $starterAdditionalFiles ` + -defaultArchitectureFilePath $bootstrapParameters.$architectureFilePathInputName.DefaultValue ` + -architectureName $architectureName + + if ($null -ne $architectureFile.ArchitectureFilePath) { + $inputConfig | Add-Member -NotePropertyName $architectureFilePathInputName -NotePropertyValue @{ + Value = $architectureFile.ArchitectureFilePath + Source = "calculated" + Sensitive = $false + } + $architectureFileToRemove = $architectureFile.DefaultFileToRemove + } + } + Write-Verbose "Final Input config: $(ConvertTo-Json $inputConfig -Depth 100)" # Getting the input for the bootstrap module @@ -283,6 +311,11 @@ function New-Bootstrap { } } + if ($null -ne $architectureFileToRemove -and (Test-Path $architectureFileToRemove)) { + Write-ToConsoleLog "Removing the starter architecture file $architectureFileToRemove because your file '$($inputConfig.terraform_architecture_file_path.Value)' defines the same architecture." + Remove-Item -Path $architectureFileToRemove -Force + } + # Running terraform init and apply Write-ToConsoleLog "Thank you for providing those inputs, we are now initializing and applying Terraform to bootstrap your environment..." -IsSuccess diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 new file mode 100644 index 00000000..9d8c6cd2 --- /dev/null +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 @@ -0,0 +1,93 @@ +function Resolve-TerraformArchitectureFile { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string] $starterModulePath, + + [Parameter(Mandatory = $false)] + [string[]] $starterAdditionalFiles = @(), + + [Parameter(Mandatory = $true)] + [string] $defaultArchitectureFilePath, + + [Parameter(Mandatory = $false)] + [string] $architectureName = "" + ) + + $result = [PSCustomObject]@{ + ArchitectureFilePath = $null + DefaultFileToRemove = $null + } + + $architectureFilePattern = '\.alz_architecture_definition\.(json|ya?ml)$' + + function Get-ArchitectureName { + param([string] $path) + $content = Get-Content -Path $path -Raw + if ($path -match '\.json$') { + return ($content | ConvertFrom-Json).name + } + return ($content | ConvertFrom-Yaml).name + } + + $userArchitectureFiles = @() + foreach ($additionalFile in $starterAdditionalFiles) { + if (Test-Path $additionalFile -PathType Container) { + $folder = Get-Item -Path $additionalFile + $files = Get-ChildItem -Path $folder.FullName -File -Recurse -Force | Where-Object { $_.Name -match $architectureFilePattern } + foreach ($file in $files) { + $relativePath = [System.IO.Path]::GetRelativePath($folder.FullName, $file.FullName).Replace('\', '/') + $userArchitectureFiles += [PSCustomObject]@{ + SourcePath = $file.FullName + DestinationPath = "$($folder.Name)/$relativePath" + } + } + } elseif ((Test-Path $additionalFile -PathType Leaf) -and ([System.IO.Path]::GetFileName($additionalFile) -match $architectureFilePattern)) { + $userArchitectureFiles += [PSCustomObject]@{ + SourcePath = (Get-Item -Path $additionalFile).FullName + DestinationPath = [System.IO.Path]::GetFileName($additionalFile) + } + } + } + + if ($userArchitectureFiles.Count -eq 0) { + return $result + } + + $defaultFileFullPath = Join-Path -Path $starterModulePath -ChildPath $defaultArchitectureFilePath + $defaultArchitectureName = $null + if (Test-Path $defaultFileFullPath -PathType Leaf) { + $defaultArchitectureName = Get-ArchitectureName -path $defaultFileFullPath + } + + $targetArchitectureName = if ([string]::IsNullOrWhiteSpace($architectureName)) { $defaultArchitectureName } else { $architectureName } + + $candidates = @($userArchitectureFiles | Where-Object { + $null -eq $targetArchitectureName -or (Get-ArchitectureName -path $_.SourcePath) -eq $targetArchitectureName + }) + + if ($candidates.Count -eq 0) { + Write-ToConsoleLog "Found architecture definition files ($($userArchitectureFiles.DestinationPath -join ', ')) but none has the architecture name '$targetArchitectureName', so the bootstrap will use '$defaultArchitectureFilePath'. Set 'terraform_architecture_file_path' in your inputs to choose a file." -IsWarning + return $result + } + + if ($candidates.Count -gt 1) { + $message = "Found more than one architecture definition file for architecture '$targetArchitectureName': $($candidates.DestinationPath -join ', '). Remove the duplicates or set 'terraform_architecture_file_path' in your inputs to choose a file." + Write-ToConsoleLog $message -IsError + throw $message + } + + $selectedPath = $candidates[0].DestinationPath + if ($selectedPath -eq $defaultArchitectureFilePath.Replace('\', '/')) { + return $result + } + + Write-Verbose "Using architecture definition file '$selectedPath' for the bootstrap." + $result.ArchitectureFilePath = $selectedPath + + if ($null -ne $defaultArchitectureName -and $defaultArchitectureName -eq $targetArchitectureName) { + $result.DefaultFileToRemove = $defaultFileFullPath + } + + return $result +} diff --git a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 new file mode 100644 index 00000000..c4290387 --- /dev/null +++ b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 @@ -0,0 +1,129 @@ +#------------------------------------------------------------------------- +Set-Location -Path $PSScriptRoot +#------------------------------------------------------------------------- +$ModuleName = 'ALZ' +$PathToManifest = [System.IO.Path]::Combine('..', '..', '..', $ModuleName, "$ModuleName.psd1") +#------------------------------------------------------------------------- +if (Get-Module -Name $ModuleName -ErrorAction 'SilentlyContinue') { + Remove-Module -Name $ModuleName -Force +} +Import-Module $PathToManifest -Force +#------------------------------------------------------------------------- + +InModuleScope 'ALZ' { + Describe 'New-Bootstrap architecture file handling' -Tag Unit { + BeforeAll { + Import-Module powershell-yaml -ErrorAction Stop + + function Add-TestFile { + param([string] $Path, [string] $Content) + New-Item -Path (Split-Path $Path -Parent) -ItemType Directory -Force | Out-Null + Set-Content -Path $Path -Value $Content + } + + function Get-TestInputConfig { + [PSCustomObject]@{ + starter_module_name = @{ Value = 'platform_landing_zone'; Source = 'input'; Sensitive = $false } + } + } + + function Invoke-TestBootstrap { + param([PSCustomObject] $InputConfig) + New-Bootstrap ` + -iac 'terraform' ` + -bootstrapDetails ([PSCustomObject]@{ Value = [PSCustomObject]@{ location = 'alz/local' } }) ` + -inputConfig $InputConfig ` + -bootstrapTargetPath $bootstrapTargetPath ` + -bootstrapRelease 'v1.0.0' ` + -hasStarter ` + -starterTargetPath $starterTargetPath ` + -starterRelease 'v2.0.0' ` + -starterConfig ([PSCustomObject]@{ starter_modules = [PSCustomObject]@{ Value = [PSCustomObject]@{ platform_landing_zone = [PSCustomObject]@{ location = 'platform_landing_zone' } } } }) ` + -hclParserToolPath 'hcl2json' ` + -starterAdditionalFiles @($userLibPath) ` + -autoApprove + } + } + + BeforeEach { + $root = Join-Path $TestDrive ([guid]::NewGuid().ToString()) + $bootstrapTargetPath = Join-Path $root 'boot-module' + $starterTargetPath = Join-Path $root 'starter-module' + $userLibPath = Join-Path $root 'config/lib' + $bootstrapTfvarsPath = Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfvars.json' + $starterModulePath = Join-Path $starterTargetPath 'v2.0.0/platform_landing_zone' + $starterDefaultFile = Join-Path $starterModulePath 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + + Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/variables.tf') -Content '' + Add-TestFile -Path (Join-Path $starterModulePath 'variables.tf') -Content '' + Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups: []" + New-Item -Path $userLibPath -ItemType Directory -Force | Out-Null + + Mock -CommandName Convert-HCLVariablesToInputConfig -ParameterFilter { $targetVariableFile -like '*boot-module*' } -MockWith { + [PSCustomObject]@{ + terraform_architecture_file_path = [PSCustomObject]@{ + Value = '' + Source = 'input' + DefaultValue = 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Description = '' + Sensitive = $false + } + } + } + Mock -CommandName Convert-HCLVariablesToInputConfig -ParameterFilter { $targetVariableFile -like '*starter-module*' } -MockWith { [PSCustomObject]@{} } + Mock -CommandName Invoke-Terraform -MockWith { } + Mock -CommandName Write-ToConsoleLog -MockWith { } + } + + It 'passes a renamed architecture file to the bootstrap and removes the duplicate default' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + Test-Path (Join-Path $starterModulePath 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml') | Should -BeTrue + Test-Path $starterDefaultFile | Should -BeFalse + } + + It 'keeps the default architecture file path when the user lib has no architecture file' { + Add-TestFile -Path (Join-Path $userLibPath 'archetype_definitions/root_custom.alz_archetype_override.yaml') -Content 'name: root_custom' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + } + + It 'keeps an explicit architecture file path input and the default file' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + $inputConfig = Get-TestInputConfig + $inputConfig | Add-Member -NotePropertyName 'terraform_architecture_file_path' -NotePropertyValue @{ Value = 'lib/architecture_definitions/explicit.alz_architecture_definition.yaml'; Source = '.yaml'; Sensitive = $false } + + Invoke-TestBootstrap -InputConfig $inputConfig + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/explicit.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + } + + It 'uses the architecture name from the platform landing zone inputs' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.json') -Content '{ "name": "contoso" }' + $inputConfig = Get-TestInputConfig + $inputConfig | Add-Member -NotePropertyName 'management_group_settings' -NotePropertyValue @{ Value = [PSCustomObject]@{ architecture_name = 'contoso' }; Source = '.tfvars'; Sensitive = $false } + + Invoke-TestBootstrap -InputConfig $inputConfig + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.json' + Test-Path $starterDefaultFile | Should -BeTrue + } + + It 'gives the same result when run again on the same output folder' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeFalse + } + } +} diff --git a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 new file mode 100644 index 00000000..9c4f771e --- /dev/null +++ b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 @@ -0,0 +1,119 @@ +#------------------------------------------------------------------------- +Set-Location -Path $PSScriptRoot +#------------------------------------------------------------------------- +$ModuleName = 'ALZ' +$PathToManifest = [System.IO.Path]::Combine('..', '..', '..', $ModuleName, "$ModuleName.psd1") +#------------------------------------------------------------------------- +if (Get-Module -Name $ModuleName -ErrorAction 'SilentlyContinue') { + Remove-Module -Name $ModuleName -Force +} +Import-Module $PathToManifest -Force +#------------------------------------------------------------------------- + +InModuleScope 'ALZ' { + Describe 'Resolve-TerraformArchitectureFile Function Tests' -Tag Unit { + BeforeAll { + Import-Module powershell-yaml -ErrorAction Stop + $defaultPath = 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + + function Add-TestFile { + param([string] $Path, [string] $Content) + New-Item -Path (Split-Path $Path -Parent) -ItemType Directory -Force | Out-Null + Set-Content -Path $Path -Value $Content + } + } + + BeforeEach { + $root = Join-Path $TestDrive ([guid]::NewGuid().ToString()) + $starterPath = Join-Path $root 'starter' + $userLibPath = Join-Path $root 'config/lib' + $starterDefaultFile = Join-Path $starterPath 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups: []" + New-Item -Path $userLibPath -ItemType Directory -Force | Out-Null + } + + It 'makes no change when the user lib has no architecture file' { + Add-TestFile -Path (Join-Path $userLibPath 'archetype_definitions/root_custom.alz_archetype_override.yaml') -Content 'name: root_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + $result.DefaultFileToRemove | Should -BeNullOrEmpty + } + + It 'makes no change when the user architecture file replaces the default path' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/alz_custom.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + $result.DefaultFileToRemove | Should -BeNullOrEmpty + } + + It 'selects a renamed yaml file with the default architecture name and removes the duplicate default' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + $result.DefaultFileToRemove | Should -Be $starterDefaultFile + } + + It 'selects a renamed json file by the architecture name input and keeps the differently named default' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.json') -Content '{ "name": "contoso", "management_groups": [] }' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -architectureName 'contoso' + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.json' + $result.DefaultFileToRemove | Should -BeNullOrEmpty + } + + It 'keeps the subfolder of a nested yml file' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/custom/contoso.alz_architecture_definition.yml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/custom/contoso.alz_architecture_definition.yml' + } + + It 'throws when more than one user file declares the target architecture name' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/fabrikam.alz_architecture_definition.json') -Content '{ "name": "alz_custom" }' + + { Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath } | + Should -Throw "*lib/architecture_definitions/contoso.alz_architecture_definition.yaml*lib/architecture_definitions/fabrikam.alz_architecture_definition.json*terraform_architecture_file_path*" + Test-Path $starterDefaultFile | Should -BeTrue + } + + It 'makes no change and warns when no user file declares the target architecture name' { + Mock -CommandName Write-ToConsoleLog -MockWith { } + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: contoso' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + $result.DefaultFileToRemove | Should -BeNullOrEmpty + Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like '*alz_custom*' } + } + + It 'selects the only user file when a previous run already removed the default' { + Remove-Item -Path $starterDefaultFile -Force + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + $result.DefaultFileToRemove | Should -BeNullOrEmpty + } + + It 'selects an architecture file passed directly as an additional file' { + $file = Join-Path $root 'config/contoso.alz_architecture_definition.yaml' + Add-TestFile -Path $file -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($file) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -Be 'contoso.alz_architecture_definition.yaml' + $result.DefaultFileToRemove | Should -Be $starterDefaultFile + } + } +} From 4b338f08fed5315b58410e90c5eb960825fb6ca8 Mon Sep 17 00:00:00 2001 From: "Prince Nagar (BEYONDSOFT CONSULTING INC)" Date: Wed, 25 Nov 2026 12:34:47 +0530 Subject: [PATCH 2/6] fix(deploy-accelerator): keep existing setups unchanged when resolving architecture files Review follow-up for the renamed architecture file support. - Take the target architecture name from the starter code (a hardcoded architecture_name, the input, or the optional() default) so a rerun after the default file was removed resolves the same file. - Only count files in the lib folder, matched with the lower-case extensions the bootstrap reads, and leave everything unchanged when a user file lands on the default path, so the dedupe can never remove the user's own file. - Skip files that do not parse or have no text name, and warn instead of failing when powershell-yaml is not loaded. - Keep the default path when the bootstrap state already manages a different intermediate root management group; switching would replace it. - Warn when the default file is missing from a reused starter folder. Refs Azure/Azure-Landing-Zones#4068 --- .../New-Bootstrap.ps1 | 14 +- .../Resolve-TerraformArchitectureFile.ps1 | 131 +++++++++++++----- .../Unit/Private/New-Bootstrap.Tests.ps1 | 43 ++++++ ...esolve-TerraformArchitectureFile.Tests.ps1 | 116 ++++++++++++++-- 4 files changed, 257 insertions(+), 47 deletions(-) diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 index 71fad7f6..e79d528b 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 @@ -193,11 +193,23 @@ function New-Bootstrap { $architectureName = $inputConfig.management_group_settings.Value.architecture_name } + $existingRootManagementGroupId = "" + $bootstrapStatePath = Join-Path -Path $bootstrapModulePath -ChildPath "terraform.tfstate" + if (Test-Path -LiteralPath $bootstrapStatePath) { + try { + $bootstrapState = Get-Content -LiteralPath $bootstrapStatePath -Raw | ConvertFrom-Json + $existingRootManagementGroupId = @($bootstrapState.resources | Where-Object { $_.type -eq "azapi_resource" -and $_.name -eq "intermediate_root_management_group" } | ForEach-Object { $_.instances } | ForEach-Object { $_.attributes.name }) | Select-Object -First 1 + } catch { + Write-Verbose "Could not read the bootstrap state at ${bootstrapStatePath}: $_" + } + } + $architectureFile = Resolve-TerraformArchitectureFile ` -starterModulePath $starterRootModuleFolderPath ` -starterAdditionalFiles $starterAdditionalFiles ` -defaultArchitectureFilePath $bootstrapParameters.$architectureFilePathInputName.DefaultValue ` - -architectureName $architectureName + -architectureName $architectureName ` + -existingRootManagementGroupId $existingRootManagementGroupId if ($null -ne $architectureFile.ArchitectureFilePath) { $inputConfig | Add-Member -NotePropertyName $architectureFilePathInputName -NotePropertyValue @{ diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 index 9d8c6cd2..4483cf11 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 @@ -11,7 +11,10 @@ function Resolve-TerraformArchitectureFile { [string] $defaultArchitectureFilePath, [Parameter(Mandatory = $false)] - [string] $architectureName = "" + [string] $architectureName = "", + + [Parameter(Mandatory = $false)] + [string] $existingRootManagementGroupId = "" ) $result = [PSCustomObject]@{ @@ -19,73 +22,131 @@ function Resolve-TerraformArchitectureFile { DefaultFileToRemove = $null } - $architectureFilePattern = '\.alz_architecture_definition\.(json|ya?ml)$' + $pathComparison = if ($IsWindows) { [System.StringComparison]::OrdinalIgnoreCase } else { [System.StringComparison]::Ordinal } + $defaultArchitectureFilePath = $defaultArchitectureFilePath.Replace('\', '/') + $libraryFolderName = $defaultArchitectureFilePath.Split('/')[0] + $defaultFileFullPath = Join-Path -Path $starterModulePath -ChildPath $defaultArchitectureFilePath + $defaultFileExists = Test-Path -LiteralPath $defaultFileFullPath -PathType Leaf - function Get-ArchitectureName { + function Get-ArchitectureDefinition { param([string] $path) - $content = Get-Content -Path $path -Raw - if ($path -match '\.json$') { - return ($content | ConvertFrom-Json).name + try { + $content = Get-Content -LiteralPath $path -Raw + $definition = if ($path.EndsWith('.json')) { $content | ConvertFrom-Json } else { $content | ConvertFrom-Yaml } + } catch { + Write-Verbose "Could not parse architecture definition file ${path}: $_" + return $null + } + if ($null -eq $definition -or $definition.name -isnot [string] -or [string]::IsNullOrWhiteSpace($definition.name)) { + return $null + } + $rootManagementGroupId = @($definition.management_groups | Where-Object { $null -ne $_ -and $null -eq $_.parent_id } | ForEach-Object { $_.id }) + return [PSCustomObject]@{ + Name = $definition.name + RootManagementGroupId = if ($rootManagementGroupId.Count -eq 1) { $rootManagementGroupId[0] } else { $null } + } + } + + function Complete-WithoutChange { + if (-not $defaultFileExists) { + Write-ToConsoleLog "The bootstrap will read '$defaultArchitectureFilePath', but it is missing from the starter module at $starterModulePath. If an earlier run removed it, run again with -replaceFiles or set 'terraform_architecture_file_path' in your inputs." -IsWarning } - return ($content | ConvertFrom-Yaml).name + return $result } $userArchitectureFiles = @() foreach ($additionalFile in $starterAdditionalFiles) { - if (Test-Path $additionalFile -PathType Container) { - $folder = Get-Item -Path $additionalFile - $files = Get-ChildItem -Path $folder.FullName -File -Recurse -Force | Where-Object { $_.Name -match $architectureFilePattern } - foreach ($file in $files) { - $relativePath = [System.IO.Path]::GetRelativePath($folder.FullName, $file.FullName).Replace('\', '/') - $userArchitectureFiles += [PSCustomObject]@{ - SourcePath = $file.FullName - DestinationPath = "$($folder.Name)/$relativePath" - } - } - } elseif ((Test-Path $additionalFile -PathType Leaf) -and ([System.IO.Path]::GetFileName($additionalFile) -match $architectureFilePattern)) { + if (-not (Test-Path -LiteralPath $additionalFile -PathType Container)) { + continue + } + $folderName = ([System.IO.DirectoryInfo]::new($additionalFile)).Name + if (-not [string]::Equals($folderName, $libraryFolderName, $pathComparison)) { + continue + } + $folderPath = (Resolve-Path -LiteralPath $additionalFile).Path + $files = Get-ChildItem -LiteralPath $folderPath -File -Recurse -Force | Where-Object { $_.Name -cmatch '\.alz_architecture_definition\.(json|yaml|yml)$' } + foreach ($file in $files) { + $relativePath = [System.IO.Path]::GetRelativePath($folderPath, $file.FullName).Replace('\', '/') $userArchitectureFiles += [PSCustomObject]@{ - SourcePath = (Get-Item -Path $additionalFile).FullName - DestinationPath = [System.IO.Path]::GetFileName($additionalFile) + SourcePath = $file.FullName + DestinationPath = "$folderName/$relativePath" } } } if ($userArchitectureFiles.Count -eq 0) { + return Complete-WithoutChange + } + + if (@($userArchitectureFiles | Where-Object { [string]::Equals($_.DestinationPath, $defaultArchitectureFilePath, $pathComparison) }).Count -gt 0) { return $result } - $defaultFileFullPath = Join-Path -Path $starterModulePath -ChildPath $defaultArchitectureFilePath - $defaultArchitectureName = $null - if (Test-Path $defaultFileFullPath -PathType Leaf) { - $defaultArchitectureName = Get-ArchitectureName -path $defaultFileFullPath + $needsYaml = @($userArchitectureFiles | Where-Object { -not $_.SourcePath.EndsWith('.json') }).Count -gt 0 -or ($defaultFileExists -and -not $defaultFileFullPath.EndsWith('.json')) + if ($needsYaml -and $null -eq (Get-Command -Name ConvertFrom-Yaml -ErrorAction SilentlyContinue)) { + Write-ToConsoleLog "Found architecture definition files ($($userArchitectureFiles.DestinationPath -join ', ')) but the powershell-yaml module is not available to read them, so the bootstrap will use '$defaultArchitectureFilePath'. Install powershell-yaml or set 'terraform_architecture_file_path' in your inputs." -IsWarning + return Complete-WithoutChange } - $targetArchitectureName = if ([string]::IsNullOrWhiteSpace($architectureName)) { $defaultArchitectureName } else { $architectureName } + $defaultDefinition = if ($defaultFileExists) { Get-ArchitectureDefinition -path $defaultFileFullPath } else { $null } + + $starterArchitectureNames = @(Get-ChildItem -LiteralPath $starterModulePath -Filter '*.tf' -File -ErrorAction SilentlyContinue | ForEach-Object { Get-Content -LiteralPath $_.FullName -Raw }) + $fixedNames = @($starterArchitectureNames | ForEach-Object { [regex]::Matches($_, '(?m)^\s*architecture_name\s*=\s*"([^"$]+)"') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) + $optionalDefaultNames = @($starterArchitectureNames | ForEach-Object { [regex]::Matches($_, 'architecture_name\s*=\s*optional\(\s*string\s*,\s*"([^"$]+)"\s*\)') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) + + $targetArchitectureName = $null + if ($fixedNames.Count -eq 1) { + $targetArchitectureName = $fixedNames[0] + } elseif (-not [string]::IsNullOrWhiteSpace($architectureName)) { + $targetArchitectureName = $architectureName + } elseif ($optionalDefaultNames.Count -eq 1) { + $targetArchitectureName = $optionalDefaultNames[0] + } elseif ($null -ne $defaultDefinition) { + $targetArchitectureName = $defaultDefinition.Name + } + + $validFiles = @() + foreach ($userArchitectureFile in $userArchitectureFiles) { + $definition = Get-ArchitectureDefinition -path $userArchitectureFile.SourcePath + if ($null -eq $definition) { + Write-ToConsoleLog "Skipping architecture definition file '$($userArchitectureFile.DestinationPath)': it could not be read or has no name." -IsWarning + continue + } + $validFiles += [PSCustomObject]@{ + DestinationPath = $userArchitectureFile.DestinationPath + Name = $definition.Name + RootManagementGroupId = $definition.RootManagementGroupId + } + } - $candidates = @($userArchitectureFiles | Where-Object { - $null -eq $targetArchitectureName -or (Get-ArchitectureName -path $_.SourcePath) -eq $targetArchitectureName - }) + $candidates = @($validFiles | Where-Object { $null -eq $targetArchitectureName -or $_.Name -ceq $targetArchitectureName }) if ($candidates.Count -eq 0) { Write-ToConsoleLog "Found architecture definition files ($($userArchitectureFiles.DestinationPath -join ', ')) but none has the architecture name '$targetArchitectureName', so the bootstrap will use '$defaultArchitectureFilePath'. Set 'terraform_architecture_file_path' in your inputs to choose a file." -IsWarning - return $result + return Complete-WithoutChange } if ($candidates.Count -gt 1) { + if ($null -eq $targetArchitectureName) { + Write-ToConsoleLog "Found more than one architecture definition file ($($candidates.DestinationPath -join ', ')) and could not tell which one the starter module uses, so the bootstrap will use '$defaultArchitectureFilePath'. Set 'terraform_architecture_file_path' in your inputs to choose a file." -IsWarning + return Complete-WithoutChange + } $message = "Found more than one architecture definition file for architecture '$targetArchitectureName': $($candidates.DestinationPath -join ', '). Remove the duplicates or set 'terraform_architecture_file_path' in your inputs to choose a file." Write-ToConsoleLog $message -IsError throw $message } - $selectedPath = $candidates[0].DestinationPath - if ($selectedPath -eq $defaultArchitectureFilePath.Replace('\', '/')) { - return $result + $selected = $candidates[0] + + if (-not [string]::IsNullOrWhiteSpace($existingRootManagementGroupId) -and $selected.RootManagementGroupId -cne $existingRootManagementGroupId) { + Write-ToConsoleLog "Your bootstrap manages the intermediate root management group '$existingRootManagementGroupId'. Using '$($selected.DestinationPath)' would change it to '$($selected.RootManagementGroupId)', so the bootstrap will keep using '$defaultArchitectureFilePath'. Set 'terraform_architecture_file_path' in your inputs to switch." -IsWarning + return Complete-WithoutChange } - Write-Verbose "Using architecture definition file '$selectedPath' for the bootstrap." - $result.ArchitectureFilePath = $selectedPath + Write-Verbose "Using architecture definition file '$($selected.DestinationPath)' for the bootstrap." + $result.ArchitectureFilePath = $selected.DestinationPath - if ($null -ne $defaultArchitectureName -and $defaultArchitectureName -eq $targetArchitectureName) { + if ($null -ne $defaultDefinition -and $defaultDefinition.Name -ceq $selected.Name) { $result.DefaultFileToRemove = $defaultFileFullPath } diff --git a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 index c4290387..b5232d88 100644 --- a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 +++ b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 @@ -125,5 +125,48 @@ InModuleScope 'ALZ' { (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' Test-Path $starterDefaultFile | Should -BeFalse } + + It 'keeps the default when the architecture file path is set as a TF_VAR environment variable' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + $env:TF_VAR_terraform_architecture_file_path = 'lib/architecture_definitions/explicit.alz_architecture_definition.yaml' + try { + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + } finally { + Remove-Item -Path Env:\TF_VAR_terraform_architecture_file_path + } + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).PSObject.Properties.Name | Should -Not -Contain 'terraform_architecture_file_path' + Test-Path $starterDefaultFile | Should -BeTrue + } + + It 'uses the starter default architecture name when the inputs omit it' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + $inputConfig = Get-TestInputConfig + $inputConfig | Add-Member -NotePropertyName 'management_group_settings' -NotePropertyValue @{ Value = [PSCustomObject]@{ location = 'uksouth' }; Source = '.tfvars'; Sensitive = $false } + + Invoke-TestBootstrap -InputConfig $inputConfig + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + } + + It 'stops before deleting anything when two user files declare the same architecture' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/fabrikam.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + { Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) } | Should -Throw '*more than one architecture definition file*' + + Test-Path $starterDefaultFile | Should -BeTrue + Should -Invoke -CommandName Invoke-Terraform -Times 0 + } + + It 'keeps the default when the bootstrap state manages a different root management group' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: contoso`n parent_id: null" + Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -Content '{ "version": 4, "resources": [ { "module": "module.azure[0]", "mode": "managed", "type": "azapi_resource", "name": "intermediate_root_management_group", "instances": [ { "index_key": 0, "attributes": { "name": "alz" } } ] } ] }' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + } } } diff --git a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 index 9c4f771e..4a6c3868 100644 --- a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 +++ b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 @@ -24,11 +24,13 @@ InModuleScope 'ALZ' { } BeforeEach { + Mock -CommandName Write-ToConsoleLog -MockWith { } $root = Join-Path $TestDrive ([guid]::NewGuid().ToString()) $starterPath = Join-Path $root 'starter' $userLibPath = Join-Path $root 'config/lib' - $starterDefaultFile = Join-Path $starterPath 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' - Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups: []" + $starterDefaultFile = Join-Path $starterPath $defaultPath + Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" + Add-TestFile -Path (Join-Path $starterPath 'variables.management.tf') -Content 'variable "management_group_settings" { type = object({ architecture_name = optional(string, "alz_custom") }) }' New-Item -Path $userLibPath -ItemType Directory -Force | Out-Null } @@ -41,8 +43,9 @@ InModuleScope 'ALZ' { $result.DefaultFileToRemove | Should -BeNullOrEmpty } - It 'makes no change when the user architecture file replaces the default path' { - Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/alz_custom.alz_architecture_definition.yaml') -Content 'name: alz_custom' + It 'makes no change when a user file replaces the default path, even with another file for the same architecture' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/alz_custom.alz_architecture_definition.yaml') -Content 'name: foo' + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath @@ -82,23 +85,22 @@ InModuleScope 'ALZ' { { Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath } | Should -Throw "*lib/architecture_definitions/contoso.alz_architecture_definition.yaml*lib/architecture_definitions/fabrikam.alz_architecture_definition.json*terraform_architecture_file_path*" - Test-Path $starterDefaultFile | Should -BeTrue } It 'makes no change and warns when no user file declares the target architecture name' { - Mock -CommandName Write-ToConsoleLog -MockWith { } Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: contoso' $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath $result.ArchitectureFilePath | Should -BeNullOrEmpty $result.DefaultFileToRemove | Should -BeNullOrEmpty - Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like '*alz_custom*' } + Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like "*none has the architecture name 'alz_custom'*" } } - It 'selects the only user file when a previous run already removed the default' { + It 'selects the same file on a rerun after the default was removed, using the starter variable default' { Remove-Item -Path $starterDefaultFile -Force Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/sandbox.alz_architecture_definition.yaml') -Content 'name: sandbox' $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath @@ -106,14 +108,106 @@ InModuleScope 'ALZ' { $result.DefaultFileToRemove | Should -BeNullOrEmpty } - It 'selects an architecture file passed directly as an additional file' { + It 'makes no change without a starter architecture name when user files have different names' { + Remove-Item -Path $starterDefaultFile, (Join-Path $starterPath 'variables.management.tf') -Force + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: contoso' + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/sandbox.alz_architecture_definition.yaml') -Content 'name: sandbox' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*could not tell which one*' } + } + + It 'follows an architecture name the starter hardcodes over the input' { + Remove-Item -Path (Join-Path $starterPath 'variables.management.tf') -Force + Add-TestFile -Path (Join-Path $starterPath 'main.tf') -Content "module `"alz`" {`n architecture_name = `"alz_custom`"`n}" + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: contoso' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -architectureName 'contoso' + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + } + + It 'ignores architecture files outside the library folder' { $file = Join-Path $root 'config/contoso.alz_architecture_definition.yaml' Add-TestFile -Path $file -Content 'name: alz_custom' + $otherFolder = Join-Path $root 'config/templates' + Add-TestFile -Path (Join-Path $otherFolder 'fabrikam.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($file, $otherFolder) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + $result.DefaultFileToRemove | Should -BeNullOrEmpty + } + + It 'ignores extensions in another case than the bootstrap reads' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.YAML') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + } - $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($file) -defaultArchitectureFilePath $defaultPath + It 'compares the default path with the case rules of the file system' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/ALZ_custom.alz_architecture_definition.yaml') -Content 'name: alz_custom' - $result.ArchitectureFilePath | Should -Be 'contoso.alz_architecture_definition.yaml' + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + if ($IsWindows) { + $result.ArchitectureFilePath | Should -BeNullOrEmpty + } else { + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/ALZ_custom.alz_architecture_definition.yaml' + } + } + + It 'skips files that cannot be read or whose name is not text' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/broken.alz_architecture_definition.yaml') -Content "name: [alz_custom`n : :" + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/flag.alz_architecture_definition.yaml') -Content 'name: true' + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + Should -Invoke -CommandName Write-ToConsoleLog -Times 2 -ParameterFilter { $IsWarning -and "$Messages" -like 'Skipping architecture definition file*' } + } + + It 'makes no change and warns when the powershell-yaml module is not available' { + Mock -CommandName Get-Command -ParameterFilter { $Name -eq 'ConvertFrom-Yaml' } -MockWith { $null } + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like '*powershell-yaml*' } + } + + It 'keeps the default when the existing bootstrap manages a different root management group' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: contoso`n parent_id: null" + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -existingRootManagementGroupId 'alz' + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + $result.DefaultFileToRemove | Should -BeNullOrEmpty + Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like "*manages the intermediate root management group 'alz'*'contoso'*" } + } + + It 'switches when the existing bootstrap manages the same root management group' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -existingRootManagementGroupId 'alz' + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' $result.DefaultFileToRemove | Should -Be $starterDefaultFile } + + It 'warns when the default file is missing and nothing replaces it' { + Remove-Item -Path $starterDefaultFile -Force + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -BeNullOrEmpty + Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like '*-replaceFiles*' } + } } } From d92471446fd2bb1419a715e16ac89f5fec6bde22 Mon Sep 17 00:00:00 2001 From: "Prince Nagar (BEYONDSOFT CONSULTING INC)" Date: Wed, 25 Nov 2026 12:45:47 +0530 Subject: [PATCH 3/6] fix(deploy-accelerator): harden architecture file resolution after second review - Compare the default path case-insensitively on every OS (macOS file systems are case-insensitive) and require the lib folder name to match exactly. - Stop with an error when the bootstrap state manages a root management group that neither the selected file nor the default uses; read only managed, non-deposed state instances and skip resolution when the state is unreadable or names more than one root. - Ignore architecture_name in block comments and expressions in starter code. - Count a file once when two lib folders copy it to the same destination. - Skip resolution when TF_VAR_management_group_settings overrides the input. Refs Azure/Azure-Landing-Zones#4068 --- .../New-Bootstrap.ps1 | 44 ++++++++++++------- .../Resolve-TerraformArchitectureFile.ps1 | 21 ++++++--- .../Unit/Private/New-Bootstrap.Tests.ps1 | 34 +++++++++++++- ...esolve-TerraformArchitectureFile.Tests.ps1 | 37 +++++++++++++--- 4 files changed, 107 insertions(+), 29 deletions(-) diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 index e79d528b..7adab8cf 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 @@ -186,38 +186,50 @@ function New-Bootstrap { if ($iac -eq "terraform" -and $hasStarter -and $bootstrapParameters.PSObject.Properties.Name -contains $architectureFilePathInputName -and $inputConfig.PSObject.Properties.Name -notcontains $architectureFilePathInputName -and - $null -eq [Environment]::GetEnvironmentVariable("TF_VAR_$architectureFilePathInputName")) { + $null -eq [Environment]::GetEnvironmentVariable("TF_VAR_$architectureFilePathInputName") -and + $null -eq [Environment]::GetEnvironmentVariable("TF_VAR_management_group_settings")) { $architectureName = "" if ($inputConfig.PSObject.Properties.Name -contains "management_group_settings" -and $null -ne $inputConfig.management_group_settings.Value.architecture_name) { $architectureName = $inputConfig.management_group_settings.Value.architecture_name } - $existingRootManagementGroupId = "" + $existingRootManagementGroupIds = @() + $bootstrapStateReadable = $true $bootstrapStatePath = Join-Path -Path $bootstrapModulePath -ChildPath "terraform.tfstate" if (Test-Path -LiteralPath $bootstrapStatePath) { try { $bootstrapState = Get-Content -LiteralPath $bootstrapStatePath -Raw | ConvertFrom-Json - $existingRootManagementGroupId = @($bootstrapState.resources | Where-Object { $_.type -eq "azapi_resource" -and $_.name -eq "intermediate_root_management_group" } | ForEach-Object { $_.instances } | ForEach-Object { $_.attributes.name }) | Select-Object -First 1 + $existingRootManagementGroupIds = @($bootstrapState.resources | + Where-Object { $_.mode -eq "managed" -and $_.type -eq "azapi_resource" -and $_.name -eq "intermediate_root_management_group" } | + ForEach-Object { $_.instances } | + Where-Object { $null -eq $_.PSObject.Properties["deposed"] } | + ForEach-Object { $_.attributes.name } | + Select-Object -Unique) } catch { Write-Verbose "Could not read the bootstrap state at ${bootstrapStatePath}: $_" + $bootstrapStateReadable = $false } } - $architectureFile = Resolve-TerraformArchitectureFile ` - -starterModulePath $starterRootModuleFolderPath ` - -starterAdditionalFiles $starterAdditionalFiles ` - -defaultArchitectureFilePath $bootstrapParameters.$architectureFilePathInputName.DefaultValue ` - -architectureName $architectureName ` - -existingRootManagementGroupId $existingRootManagementGroupId - - if ($null -ne $architectureFile.ArchitectureFilePath) { - $inputConfig | Add-Member -NotePropertyName $architectureFilePathInputName -NotePropertyValue @{ - Value = $architectureFile.ArchitectureFilePath - Source = "calculated" - Sensitive = $false + if (-not $bootstrapStateReadable -or $existingRootManagementGroupIds.Count -gt 1) { + Write-ToConsoleLog "Could not tell which intermediate root management group the bootstrap state at $bootstrapStatePath manages, so the bootstrap will use '$($bootstrapParameters.$architectureFilePathInputName.DefaultValue)'. Set '$architectureFilePathInputName' in your inputs to choose an architecture file." -IsWarning + } else { + $architectureFile = Resolve-TerraformArchitectureFile ` + -starterModulePath $starterRootModuleFolderPath ` + -starterAdditionalFiles $starterAdditionalFiles ` + -defaultArchitectureFilePath $bootstrapParameters.$architectureFilePathInputName.DefaultValue ` + -architectureName $architectureName ` + -existingRootManagementGroupId ($existingRootManagementGroupIds | Select-Object -First 1) + + if ($null -ne $architectureFile.ArchitectureFilePath) { + $inputConfig | Add-Member -NotePropertyName $architectureFilePathInputName -NotePropertyValue @{ + Value = $architectureFile.ArchitectureFilePath + Source = "calculated" + Sensitive = $false + } + $architectureFileToRemove = $architectureFile.DefaultFileToRemove } - $architectureFileToRemove = $architectureFile.DefaultFileToRemove } } diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 index 4483cf11..08b16f82 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 @@ -22,7 +22,7 @@ function Resolve-TerraformArchitectureFile { DefaultFileToRemove = $null } - $pathComparison = if ($IsWindows) { [System.StringComparison]::OrdinalIgnoreCase } else { [System.StringComparison]::Ordinal } + $pathComparison = [System.StringComparison]::OrdinalIgnoreCase $defaultArchitectureFilePath = $defaultArchitectureFilePath.Replace('\', '/') $libraryFolderName = $defaultArchitectureFilePath.Split('/')[0] $defaultFileFullPath = Join-Path -Path $starterModulePath -ChildPath $defaultArchitectureFilePath @@ -60,7 +60,7 @@ function Resolve-TerraformArchitectureFile { continue } $folderName = ([System.IO.DirectoryInfo]::new($additionalFile)).Name - if (-not [string]::Equals($folderName, $libraryFolderName, $pathComparison)) { + if ($folderName -cne $libraryFolderName) { continue } $folderPath = (Resolve-Path -LiteralPath $additionalFile).Path @@ -78,6 +78,12 @@ function Resolve-TerraformArchitectureFile { return Complete-WithoutChange } + $copiedArchitectureFiles = [ordered]@{} + foreach ($userArchitectureFile in $userArchitectureFiles) { + $copiedArchitectureFiles[$userArchitectureFile.DestinationPath.ToLowerInvariant()] = $userArchitectureFile + } + $userArchitectureFiles = @($copiedArchitectureFiles.Values) + if (@($userArchitectureFiles | Where-Object { [string]::Equals($_.DestinationPath, $defaultArchitectureFilePath, $pathComparison) }).Count -gt 0) { return $result } @@ -90,9 +96,9 @@ function Resolve-TerraformArchitectureFile { $defaultDefinition = if ($defaultFileExists) { Get-ArchitectureDefinition -path $defaultFileFullPath } else { $null } - $starterArchitectureNames = @(Get-ChildItem -LiteralPath $starterModulePath -Filter '*.tf' -File -ErrorAction SilentlyContinue | ForEach-Object { Get-Content -LiteralPath $_.FullName -Raw }) - $fixedNames = @($starterArchitectureNames | ForEach-Object { [regex]::Matches($_, '(?m)^\s*architecture_name\s*=\s*"([^"$]+)"') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) - $optionalDefaultNames = @($starterArchitectureNames | ForEach-Object { [regex]::Matches($_, 'architecture_name\s*=\s*optional\(\s*string\s*,\s*"([^"$]+)"\s*\)') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) + $starterTerraform = @(Get-ChildItem -LiteralPath $starterModulePath -Filter '*.tf' -File -ErrorAction SilentlyContinue | ForEach-Object { [regex]::Replace((Get-Content -LiteralPath $_.FullName -Raw), '(?s)/\*.*?\*/', '') }) + $fixedNames = @($starterTerraform | ForEach-Object { [regex]::Matches($_, '(?m)^\s*architecture_name\s*=\s*"([^"$]+)"\s*(#.*|//.*)?$') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) + $optionalDefaultNames = @($starterTerraform | ForEach-Object { [regex]::Matches($_, '(?m)^\s*architecture_name\s*=\s*optional\(\s*string\s*,\s*"([^"$]+)"\s*\)') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) $targetArchitectureName = $null if ($fixedNames.Count -eq 1) { @@ -139,6 +145,11 @@ function Resolve-TerraformArchitectureFile { $selected = $candidates[0] if (-not [string]::IsNullOrWhiteSpace($existingRootManagementGroupId) -and $selected.RootManagementGroupId -cne $existingRootManagementGroupId) { + if ($null -eq $defaultDefinition -or $defaultDefinition.RootManagementGroupId -cne $existingRootManagementGroupId) { + $message = "Your bootstrap manages the intermediate root management group '$existingRootManagementGroupId', but '$($selected.DestinationPath)' uses '$($selected.RootManagementGroupId)' and '$defaultArchitectureFilePath' does not use it either. Set 'terraform_architecture_file_path' in your inputs to choose the architecture file for the bootstrap." + Write-ToConsoleLog $message -IsError + throw $message + } Write-ToConsoleLog "Your bootstrap manages the intermediate root management group '$existingRootManagementGroupId'. Using '$($selected.DestinationPath)' would change it to '$($selected.RootManagementGroupId)', so the bootstrap will keep using '$defaultArchitectureFilePath'. Set 'terraform_architecture_file_path' in your inputs to switch." -IsWarning return Complete-WithoutChange } diff --git a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 index b5232d88..abfedbee 100644 --- a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 +++ b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 @@ -56,7 +56,7 @@ InModuleScope 'ALZ' { Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/variables.tf') -Content '' Add-TestFile -Path (Join-Path $starterModulePath 'variables.tf') -Content '' - Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups: []" + Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" New-Item -Path $userLibPath -ItemType Directory -Force | Out-Null Mock -CommandName Convert-HCLVariablesToInputConfig -ParameterFilter { $targetVariableFile -like '*boot-module*' } -MockWith { @@ -168,5 +168,37 @@ InModuleScope 'ALZ' { (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' Test-Path $starterDefaultFile | Should -BeTrue } + + It 'ignores deposed instances in the bootstrap state' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" + Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -Content '{ "version": 4, "resources": [ { "module": "module.azure[0]", "mode": "managed", "type": "azapi_resource", "name": "intermediate_root_management_group", "instances": [ { "index_key": 0, "deposed": "00000001", "attributes": { "name": "old" } }, { "index_key": 0, "attributes": { "name": "alz" } } ] } ] }' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + } + + It 'keeps the default when the bootstrap state names more than one root management group' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" + Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -Content '{ "version": 4, "resources": [ { "module": "module.azure[0]", "mode": "managed", "type": "azapi_resource", "name": "intermediate_root_management_group", "instances": [ { "index_key": 0, "attributes": { "name": "alz" } } ] }, { "module": "module.other", "mode": "managed", "type": "azapi_resource", "name": "intermediate_root_management_group", "instances": [ { "index_key": 0, "attributes": { "name": "contoso" } } ] } ] }' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*Could not tell which intermediate root management group*' } + } + + It 'keeps the default when management_group_settings is set as a TF_VAR environment variable' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + $env:TF_VAR_management_group_settings = '{ "architecture_name": "contoso" }' + try { + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + } finally { + Remove-Item -Path Env:\TF_VAR_management_group_settings + } + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + } } } diff --git a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 index 4a6c3868..ff35bfaf 100644 --- a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 +++ b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 @@ -30,7 +30,7 @@ InModuleScope 'ALZ' { $userLibPath = Join-Path $root 'config/lib' $starterDefaultFile = Join-Path $starterPath $defaultPath Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" - Add-TestFile -Path (Join-Path $starterPath 'variables.management.tf') -Content 'variable "management_group_settings" { type = object({ architecture_name = optional(string, "alz_custom") }) }' + Add-TestFile -Path (Join-Path $starterPath 'variables.management.tf') -Content "variable `"management_group_settings`" {`n type = object({`n architecture_name = optional(string, `"alz_custom`")`n })`n}" New-Item -Path $userLibPath -ItemType Directory -Force | Out-Null } @@ -149,16 +149,13 @@ InModuleScope 'ALZ' { $result.ArchitectureFilePath | Should -BeNullOrEmpty } - It 'compares the default path with the case rules of the file system' { + It 'treats a default path in another letter case as the default path' { Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/ALZ_custom.alz_architecture_definition.yaml') -Content 'name: alz_custom' $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath - if ($IsWindows) { - $result.ArchitectureFilePath | Should -BeNullOrEmpty - } else { - $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/ALZ_custom.alz_architecture_definition.yaml' - } + $result.ArchitectureFilePath | Should -BeNullOrEmpty + $result.DefaultFileToRemove | Should -BeNullOrEmpty } It 'skips files that cannot be read or whose name is not text' { @@ -201,6 +198,32 @@ InModuleScope 'ALZ' { $result.DefaultFileToRemove | Should -Be $starterDefaultFile } + It 'stops when neither the selected file nor the default uses the root management group in the bootstrap state' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: fabrikam`n parent_id: null" + + { Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -existingRootManagementGroupId 'contoso' } | + Should -Throw "*manages the intermediate root management group 'contoso'*'fabrikam'*terraform_architecture_file_path*" + } + + It 'ignores architecture names in comments and expressions in the starter code' { + Add-TestFile -Path (Join-Path $starterPath 'main.tf') -Content "/*`n architecture_name = `"old`"`n*/`nlocals {`n architecture_name = `"old`" == var.variant ? `"contoso`" : `"alz_custom`"`n}" + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + } + + It 'counts a file once when two lib folders copy it to the same destination' { + $commonLibPath = Join-Path $root 'common/lib' + Add-TestFile -Path (Join-Path $commonLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' + + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($commonLibPath, $userLibPath) -defaultArchitectureFilePath $defaultPath + + $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' + } + It 'warns when the default file is missing and nothing replaces it' { Remove-Item -Path $starterDefaultFile -Force From 535ce4251672d0a75d61da5a704fd3afce31afb7 Mon Sep 17 00:00:00 2001 From: "Prince Nagar (BEYONDSOFT CONSULTING INC)" Date: Wed, 25 Nov 2026 13:06:02 +0530 Subject: [PATCH 4/6] fix(deploy-accelerator): ignore heredoc text and keep case-distinct files apart - Strip heredoc strings as well as block comments before reading the architecture name from the starter code. - Deduplicate copied architecture files by their exact destination, so files whose paths differ only in letter case are both counted. Refs Azure/Azure-Landing-Zones#4068 --- .../Resolve-TerraformArchitectureFile.ps1 | 10 +++++++--- ...Resolve-TerraformArchitectureFile.Tests.ps1 | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 index 08b16f82..f9630d2b 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 @@ -78,9 +78,9 @@ function Resolve-TerraformArchitectureFile { return Complete-WithoutChange } - $copiedArchitectureFiles = [ordered]@{} + $copiedArchitectureFiles = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) foreach ($userArchitectureFile in $userArchitectureFiles) { - $copiedArchitectureFiles[$userArchitectureFile.DestinationPath.ToLowerInvariant()] = $userArchitectureFile + $copiedArchitectureFiles[$userArchitectureFile.DestinationPath] = $userArchitectureFile } $userArchitectureFiles = @($copiedArchitectureFiles.Values) @@ -96,7 +96,11 @@ function Resolve-TerraformArchitectureFile { $defaultDefinition = if ($defaultFileExists) { Get-ArchitectureDefinition -path $defaultFileFullPath } else { $null } - $starterTerraform = @(Get-ChildItem -LiteralPath $starterModulePath -Filter '*.tf' -File -ErrorAction SilentlyContinue | ForEach-Object { [regex]::Replace((Get-Content -LiteralPath $_.FullName -Raw), '(?s)/\*.*?\*/', '') }) + $starterTerraform = @(Get-ChildItem -LiteralPath $starterModulePath -Filter '*.tf' -File -ErrorAction SilentlyContinue | ForEach-Object { + $terraform = Get-Content -LiteralPath $_.FullName -Raw + $terraform = [regex]::Replace($terraform, '(?ms)<<-?\s*([A-Za-z_][A-Za-z0-9_]*)\s*$.*?^\s*\1\s*$', '') + [regex]::Replace($terraform, '(?s)/\*.*?\*/', '') + }) $fixedNames = @($starterTerraform | ForEach-Object { [regex]::Matches($_, '(?m)^\s*architecture_name\s*=\s*"([^"$]+)"\s*(#.*|//.*)?$') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) $optionalDefaultNames = @($starterTerraform | ForEach-Object { [regex]::Matches($_, '(?m)^\s*architecture_name\s*=\s*optional\(\s*string\s*,\s*"([^"$]+)"\s*\)') } | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique) diff --git a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 index ff35bfaf..f9207d1a 100644 --- a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 +++ b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 @@ -224,6 +224,24 @@ InModuleScope 'ALZ' { $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' } + It 'ignores architecture names inside heredoc strings in the starter code' { + Add-TestFile -Path (Join-Path $starterPath 'variables.docs.tf') -Content "variable `"example`" {`n description = < Date: Thu, 26 Nov 2026 10:46:59 +0530 Subject: [PATCH 5/6] fix(deploy-accelerator): read bootstrap state only for a renamed file and give working recovery advice - Read terraform.tfstate inside Resolve-TerraformArchitectureFile after a renamed file is selected. Users without a renamed architecture file no longer get a state warning, and an empty or unreadable state keeps the default path with a warning. - Parse the state with -AsHashtable so keys that differ only in case do not fail the read. - When the default architecture file is missing, tell users to add their file to their lib folder at the default path or set terraform_architecture_file_path. -replaceFiles only applies to the override folders, so it did not restore the file for release downloads. - Use -LiteralPath when removing the starter default file. - Add New-Bootstrap tests for unreadable and empty state and for a default layout with unreadable state; rename a test whose name did not match its setup. Refs Azure/Azure-Landing-Zones#4068 --- .../New-Bootstrap.ps1 | 52 ++++++------------- .../Resolve-TerraformArchitectureFile.ps1 | 32 +++++++++++- .../Unit/Private/New-Bootstrap.Tests.ps1 | 36 ++++++++++++- ...esolve-TerraformArchitectureFile.Tests.ps1 | 18 +++++-- 4 files changed, 94 insertions(+), 44 deletions(-) diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 index 7adab8cf..3bb37d3b 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/New-Bootstrap.ps1 @@ -194,42 +194,20 @@ function New-Bootstrap { $architectureName = $inputConfig.management_group_settings.Value.architecture_name } - $existingRootManagementGroupIds = @() - $bootstrapStateReadable = $true - $bootstrapStatePath = Join-Path -Path $bootstrapModulePath -ChildPath "terraform.tfstate" - if (Test-Path -LiteralPath $bootstrapStatePath) { - try { - $bootstrapState = Get-Content -LiteralPath $bootstrapStatePath -Raw | ConvertFrom-Json - $existingRootManagementGroupIds = @($bootstrapState.resources | - Where-Object { $_.mode -eq "managed" -and $_.type -eq "azapi_resource" -and $_.name -eq "intermediate_root_management_group" } | - ForEach-Object { $_.instances } | - Where-Object { $null -eq $_.PSObject.Properties["deposed"] } | - ForEach-Object { $_.attributes.name } | - Select-Object -Unique) - } catch { - Write-Verbose "Could not read the bootstrap state at ${bootstrapStatePath}: $_" - $bootstrapStateReadable = $false - } - } - - if (-not $bootstrapStateReadable -or $existingRootManagementGroupIds.Count -gt 1) { - Write-ToConsoleLog "Could not tell which intermediate root management group the bootstrap state at $bootstrapStatePath manages, so the bootstrap will use '$($bootstrapParameters.$architectureFilePathInputName.DefaultValue)'. Set '$architectureFilePathInputName' in your inputs to choose an architecture file." -IsWarning - } else { - $architectureFile = Resolve-TerraformArchitectureFile ` - -starterModulePath $starterRootModuleFolderPath ` - -starterAdditionalFiles $starterAdditionalFiles ` - -defaultArchitectureFilePath $bootstrapParameters.$architectureFilePathInputName.DefaultValue ` - -architectureName $architectureName ` - -existingRootManagementGroupId ($existingRootManagementGroupIds | Select-Object -First 1) - - if ($null -ne $architectureFile.ArchitectureFilePath) { - $inputConfig | Add-Member -NotePropertyName $architectureFilePathInputName -NotePropertyValue @{ - Value = $architectureFile.ArchitectureFilePath - Source = "calculated" - Sensitive = $false - } - $architectureFileToRemove = $architectureFile.DefaultFileToRemove + $architectureFile = Resolve-TerraformArchitectureFile ` + -starterModulePath $starterRootModuleFolderPath ` + -starterAdditionalFiles $starterAdditionalFiles ` + -defaultArchitectureFilePath $bootstrapParameters.$architectureFilePathInputName.DefaultValue ` + -architectureName $architectureName ` + -bootstrapStatePath (Join-Path -Path $bootstrapModulePath -ChildPath "terraform.tfstate") + + if ($null -ne $architectureFile.ArchitectureFilePath) { + $inputConfig | Add-Member -NotePropertyName $architectureFilePathInputName -NotePropertyValue @{ + Value = $architectureFile.ArchitectureFilePath + Source = "calculated" + Sensitive = $false } + $architectureFileToRemove = $architectureFile.DefaultFileToRemove } } @@ -335,9 +313,9 @@ function New-Bootstrap { } } - if ($null -ne $architectureFileToRemove -and (Test-Path $architectureFileToRemove)) { + if ($null -ne $architectureFileToRemove -and (Test-Path -LiteralPath $architectureFileToRemove)) { Write-ToConsoleLog "Removing the starter architecture file $architectureFileToRemove because your file '$($inputConfig.terraform_architecture_file_path.Value)' defines the same architecture." - Remove-Item -Path $architectureFileToRemove -Force + Remove-Item -LiteralPath $architectureFileToRemove -Force } # Running terraform init and apply diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 index f9630d2b..e298b0b1 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 @@ -14,7 +14,7 @@ function Resolve-TerraformArchitectureFile { [string] $architectureName = "", [Parameter(Mandatory = $false)] - [string] $existingRootManagementGroupId = "" + [string] $bootstrapStatePath = "" ) $result = [PSCustomObject]@{ @@ -49,7 +49,7 @@ function Resolve-TerraformArchitectureFile { function Complete-WithoutChange { if (-not $defaultFileExists) { - Write-ToConsoleLog "The bootstrap will read '$defaultArchitectureFilePath', but it is missing from the starter module at $starterModulePath. If an earlier run removed it, run again with -replaceFiles or set 'terraform_architecture_file_path' in your inputs." -IsWarning + Write-ToConsoleLog "The bootstrap will read '$defaultArchitectureFilePath', but it is missing from the starter module at $starterModulePath. If an earlier run removed it, add your architecture file to your lib folder at '$defaultArchitectureFilePath' or set 'terraform_architecture_file_path' in your inputs." -IsWarning } return $result } @@ -148,6 +148,34 @@ function Resolve-TerraformArchitectureFile { $selected = $candidates[0] + $existingRootManagementGroupIds = @() + if (-not [string]::IsNullOrWhiteSpace($bootstrapStatePath) -and (Test-Path -LiteralPath $bootstrapStatePath -PathType Leaf)) { + try { + $existingRootManagementGroupIds = & { + $ErrorActionPreference = 'Stop' + $bootstrapState = Get-Content -LiteralPath $bootstrapStatePath -Raw | ConvertFrom-Json -AsHashtable + if ($bootstrapState -isnot [hashtable]) { + throw "The bootstrap state is empty or not a JSON object." + } + , @($bootstrapState.resources | + Where-Object { $_.mode -eq "managed" -and $_.type -eq "azapi_resource" -and $_.name -eq "intermediate_root_management_group" } | + ForEach-Object { $_.instances } | + Where-Object { -not $_.ContainsKey("deposed") } | + ForEach-Object { $_.attributes.name } | + Select-Object -Unique) + } + } catch { + Write-Verbose "Could not read the bootstrap state at ${bootstrapStatePath}: $_" + $existingRootManagementGroupIds = $null + } + } + + if ($null -eq $existingRootManagementGroupIds -or $existingRootManagementGroupIds.Count -gt 1) { + Write-ToConsoleLog "Could not tell which intermediate root management group the bootstrap state at $bootstrapStatePath manages, so the bootstrap will use '$defaultArchitectureFilePath'. Set 'terraform_architecture_file_path' in your inputs to choose an architecture file." -IsWarning + return Complete-WithoutChange + } + $existingRootManagementGroupId = $existingRootManagementGroupIds | Select-Object -First 1 + if (-not [string]::IsNullOrWhiteSpace($existingRootManagementGroupId) -and $selected.RootManagementGroupId -cne $existingRootManagementGroupId) { if ($null -eq $defaultDefinition -or $defaultDefinition.RootManagementGroupId -cne $existingRootManagementGroupId) { $message = "Your bootstrap manages the intermediate root management group '$existingRootManagementGroupId', but '$($selected.DestinationPath)' uses '$($selected.RootManagementGroupId)' and '$defaultArchitectureFilePath' does not use it either. Set 'terraform_architecture_file_path' in your inputs to choose the architecture file for the bootstrap." diff --git a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 index abfedbee..50b99819 100644 --- a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 +++ b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 @@ -139,7 +139,7 @@ InModuleScope 'ALZ' { Test-Path $starterDefaultFile | Should -BeTrue } - It 'uses the starter default architecture name when the inputs omit it' { + It 'uses the default architecture file name when the inputs omit the architecture name' { Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' $inputConfig = Get-TestInputConfig $inputConfig | Add-Member -NotePropertyName 'management_group_settings' -NotePropertyValue @{ Value = [PSCustomObject]@{ location = 'uksouth' }; Source = '.tfvars'; Sensitive = $false } @@ -188,6 +188,40 @@ InModuleScope 'ALZ' { Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*Could not tell which intermediate root management group*' } } + It 'keeps the default and warns when the bootstrap state cannot be read' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: contoso`n parent_id: null" + Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -Content '{ "version": 4, "resources": [' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*Could not tell which intermediate root management group*' } + Should -Invoke -CommandName Invoke-Terraform -Times 1 + } + + It 'keeps the default and warns when the bootstrap state is empty' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: contoso`n parent_id: null" + New-Item -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -ItemType File -Force | Out-Null + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*Could not tell which intermediate root management group*' } + } + + It 'does not read the bootstrap state when the user lib has no architecture file' { + Add-TestFile -Path (Join-Path $userLibPath 'archetype_definitions/root_custom.alz_archetype_override.yaml') -Content 'name: root_custom' + Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -Content '{ "version": 4, "resources": [' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + Should -Invoke -CommandName Write-ToConsoleLog -Times 0 -ParameterFilter { $IsWarning } + } + It 'keeps the default when management_group_settings is set as a TF_VAR environment variable' { Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' $env:TF_VAR_management_group_settings = '{ "architecture_name": "contoso" }' diff --git a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 index f9207d1a..22bdce89 100644 --- a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 +++ b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 @@ -21,6 +21,11 @@ InModuleScope 'ALZ' { New-Item -Path (Split-Path $Path -Parent) -ItemType Directory -Force | Out-Null Set-Content -Path $Path -Value $Content } + + function Add-TestBootstrapState { + param([string] $Path, [string] $RootManagementGroupId) + Add-TestFile -Path $Path -Content "{ `"version`": 4, `"resources`": [ { `"mode`": `"managed`", `"type`": `"azapi_resource`", `"name`": `"intermediate_root_management_group`", `"instances`": [ { `"attributes`": { `"name`": `"$RootManagementGroupId`" } } ] } ] }" + } } BeforeEach { @@ -29,6 +34,7 @@ InModuleScope 'ALZ' { $starterPath = Join-Path $root 'starter' $userLibPath = Join-Path $root 'config/lib' $starterDefaultFile = Join-Path $starterPath $defaultPath + $statePath = Join-Path $root 'bootstrap/terraform.tfstate' Add-TestFile -Path $starterDefaultFile -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" Add-TestFile -Path (Join-Path $starterPath 'variables.management.tf') -Content "variable `"management_group_settings`" {`n type = object({`n architecture_name = optional(string, `"alz_custom`")`n })`n}" New-Item -Path $userLibPath -ItemType Directory -Force | Out-Null @@ -181,8 +187,9 @@ InModuleScope 'ALZ' { It 'keeps the default when the existing bootstrap manages a different root management group' { Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: contoso`n parent_id: null" + Add-TestBootstrapState -Path $statePath -RootManagementGroupId 'alz' - $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -existingRootManagementGroupId 'alz' + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -bootstrapStatePath $statePath $result.ArchitectureFilePath | Should -BeNullOrEmpty $result.DefaultFileToRemove | Should -BeNullOrEmpty @@ -191,8 +198,9 @@ InModuleScope 'ALZ' { It 'switches when the existing bootstrap manages the same root management group' { Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: alz`n parent_id: null" + Add-TestBootstrapState -Path $statePath -RootManagementGroupId 'alz' - $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -existingRootManagementGroupId 'alz' + $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -bootstrapStatePath $statePath $result.ArchitectureFilePath | Should -Be 'lib/architecture_definitions/contoso.alz_architecture_definition.yaml' $result.DefaultFileToRemove | Should -Be $starterDefaultFile @@ -200,8 +208,9 @@ InModuleScope 'ALZ' { It 'stops when neither the selected file nor the default uses the root management group in the bootstrap state' { Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: fabrikam`n parent_id: null" + Add-TestBootstrapState -Path $statePath -RootManagementGroupId 'contoso' - { Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -existingRootManagementGroupId 'contoso' } | + { Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath -bootstrapStatePath $statePath } | Should -Throw "*manages the intermediate root management group 'contoso'*'fabrikam'*terraform_architecture_file_path*" } @@ -248,7 +257,8 @@ InModuleScope 'ALZ' { $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath $result.ArchitectureFilePath | Should -BeNullOrEmpty - Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like '*-replaceFiles*' } + Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like "*add your architecture file to your lib folder at '$defaultPath'*terraform_architecture_file_path*" } + Should -Invoke -CommandName Write-ToConsoleLog -Times 0 -ParameterFilter { "$Messages" -like '*-replaceFiles*' } } } } From 7b9b7eb36334a56295b142510209f3d2804e29c2 Mon Sep 17 00:00:00 2001 From: "Prince Nagar (BEYONDSOFT CONSULTING INC)" Date: Thu, 26 Nov 2026 11:04:08 +0530 Subject: [PATCH 6/6] fix(deploy-accelerator): treat any unreadable state path as unknown and say move, not add - Tell users to move their architecture file to the default path inside their lib folder. Copying it there would leave two files declaring the same architecture, which alzlib rejects. - Treat a state path that exists but is not a readable JSON object, including a folder, as unknown, so the default path is kept with a warning. - Add tests for state that is a JSON array and for a folder at the state path; fix a test title. Refs Azure/Azure-Landing-Zones#4068 --- .../Resolve-TerraformArchitectureFile.ps1 | 4 ++-- .../Unit/Private/New-Bootstrap.Tests.ps1 | 23 ++++++++++++++++++- ...esolve-TerraformArchitectureFile.Tests.ps1 | 2 +- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 index e298b0b1..9f9ac03a 100644 --- a/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 +++ b/src/ALZ/Private/Deploy-Accelerator-Helpers/Resolve-TerraformArchitectureFile.ps1 @@ -49,7 +49,7 @@ function Resolve-TerraformArchitectureFile { function Complete-WithoutChange { if (-not $defaultFileExists) { - Write-ToConsoleLog "The bootstrap will read '$defaultArchitectureFilePath', but it is missing from the starter module at $starterModulePath. If an earlier run removed it, add your architecture file to your lib folder at '$defaultArchitectureFilePath' or set 'terraform_architecture_file_path' in your inputs." -IsWarning + Write-ToConsoleLog "The bootstrap will read '$defaultArchitectureFilePath', but it is missing from the starter module at $starterModulePath. If an earlier run removed it, move your architecture file to '$($defaultArchitectureFilePath.Substring($defaultArchitectureFilePath.IndexOf('/') + 1))' inside your $libraryFolderName folder, so that only one file declares the architecture, or set 'terraform_architecture_file_path' in your inputs." -IsWarning } return $result } @@ -149,7 +149,7 @@ function Resolve-TerraformArchitectureFile { $selected = $candidates[0] $existingRootManagementGroupIds = @() - if (-not [string]::IsNullOrWhiteSpace($bootstrapStatePath) -and (Test-Path -LiteralPath $bootstrapStatePath -PathType Leaf)) { + if (-not [string]::IsNullOrWhiteSpace($bootstrapStatePath) -and (Test-Path -LiteralPath $bootstrapStatePath)) { try { $existingRootManagementGroupIds = & { $ErrorActionPreference = 'Stop' diff --git a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 index 50b99819..c9a15f5a 100644 --- a/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 +++ b/src/Tests/Unit/Private/New-Bootstrap.Tests.ps1 @@ -139,7 +139,7 @@ InModuleScope 'ALZ' { Test-Path $starterDefaultFile | Should -BeTrue } - It 'uses the default architecture file name when the inputs omit the architecture name' { + It 'uses the architecture name in the starter default file when the inputs omit it' { Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content 'name: alz_custom' $inputConfig = Get-TestInputConfig $inputConfig | Add-Member -NotePropertyName 'management_group_settings' -NotePropertyValue @{ Value = [PSCustomObject]@{ location = 'uksouth' }; Source = '.tfvars'; Sensitive = $false } @@ -211,6 +211,27 @@ InModuleScope 'ALZ' { Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*Could not tell which intermediate root management group*' } } + It 'keeps the default and warns when the bootstrap state is not a JSON object' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: contoso`n parent_id: null" + Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -Content '[ ]' + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Test-Path $starterDefaultFile | Should -BeTrue + Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*Could not tell which intermediate root management group*' } + } + + It 'keeps the default and warns when the bootstrap state path is a folder' { + Add-TestFile -Path (Join-Path $userLibPath 'architecture_definitions/contoso.alz_architecture_definition.yaml') -Content "name: alz_custom`nmanagement_groups:`n - id: contoso`n parent_id: null" + New-Item -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -ItemType Directory -Force | Out-Null + + Invoke-TestBootstrap -InputConfig (Get-TestInputConfig) + + (Get-Content $bootstrapTfvarsPath -Raw | ConvertFrom-Json).terraform_architecture_file_path | Should -Be 'lib/architecture_definitions/alz_custom.alz_architecture_definition.yaml' + Should -Invoke -CommandName Write-ToConsoleLog -ParameterFilter { $IsWarning -and "$Messages" -like '*Could not tell which intermediate root management group*' } + } + It 'does not read the bootstrap state when the user lib has no architecture file' { Add-TestFile -Path (Join-Path $userLibPath 'archetype_definitions/root_custom.alz_archetype_override.yaml') -Content 'name: root_custom' Add-TestFile -Path (Join-Path $bootstrapTargetPath 'v1.0.0/alz/local/terraform.tfstate') -Content '{ "version": 4, "resources": [' diff --git a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 index 22bdce89..0b8f4576 100644 --- a/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 +++ b/src/Tests/Unit/Private/Resolve-TerraformArchitectureFile.Tests.ps1 @@ -257,7 +257,7 @@ InModuleScope 'ALZ' { $result = Resolve-TerraformArchitectureFile -starterModulePath $starterPath -starterAdditionalFiles @($userLibPath) -defaultArchitectureFilePath $defaultPath $result.ArchitectureFilePath | Should -BeNullOrEmpty - Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like "*add your architecture file to your lib folder at '$defaultPath'*terraform_architecture_file_path*" } + Should -Invoke -CommandName Write-ToConsoleLog -Times 1 -ParameterFilter { $IsWarning -and "$Messages" -like "*move your architecture file to 'architecture_definitions/alz_custom.alz_architecture_definition.yaml' inside your lib folder*terraform_architecture_file_path*" } Should -Invoke -CommandName Write-ToConsoleLog -Times 0 -ParameterFilter { "$Messages" -like '*-replaceFiles*' } } }