Pester 5 test Powershell code in pipeline
Some time ago I created Pester tests for Azure Automation Runbooks as part of a pipeline to validate code before getting checked into a repo. Though this was pre version 5 of Pester, and as 5 came around there where some changes that had to be done for everything to keep working. I will go through in this post the code I use to trigger the tests as part of a pipeline, and the tests I use. The test use both PSScriptAnalyzer and some custom AST test to validate that the Powershell code follows a certain structure layout.
The pipeline is a yaml, that triggers powershell scripts that does the heavy lifting.
The image above shows a pipeline run after updating one of the Runbooks/Modules in the repo. The powershell script below triggers running the Pester tests and creates a test report that is uploaded to AzDo and will either fail or pass the run depending on the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | <# .SYNOPSIS Build Pipeline logic that triggers Pester tests. .DESCRIPTION .PARAMETER TestScriptPath Required. Path to pester test scripts in repo. .PARAMETER TestPaths Required. Paths to scripts/modules to run test against in repo. .PARAMETER TestOutPutFilePath Optional. Path to where test results are stored. Default is: ".\Test-Pester.XML" .PARAMETER MinimumSeverityLevel Optional. Level of detail PSSscriptAnalyzer checks language in scripts. Default is: Error .NOTES AUTHOR: Morten Lerudjordet #> [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [ValidateNotNullorEmpty()] [string]$TestScriptPath, [Parameter(Mandatory=$true)] [ValidateNotNullorEmpty()] [string[]]$TestPaths, [Parameter(Mandatory=$false)] [string]$TestOutPutFilePath = ".\Test-Pester.XML", [Parameter(Mandatory=$false)] [validateSet('Information', 'Warning','Error')] [string]$MinimumSeverityLevel = 'Error' ) try { Write-Host -Object "Starting test script at time: $(get-Date -format r).`nRunning PS version: $($PSVersionTable.PSVersion)`nOn agent: $($env:computername)`n" #region Variables ############################################################ # Variables ############################################################ $PSGalleryRepositoryName = "PSGallery" $PSGalleryRepositoryURL = "https://www.powershellgallery.com/api/v2/" $PowershellGetModuleName = "PowershellGet" $PackageManagementModuleName = "PackageManagement" $ModulesToImport = @("PSScriptAnalyzer","Pester") #endregion #region Core Package Managers Module Import Import-Module -Name $PowershellGetModuleName,$PackageManagementModuleName -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to load needed package management modules" Write-Error -Message "Failed to load needed package management modules" -ErrorAction Stop } Write-Host -Object "$PowershellGetModuleName version: $((Get-Module -Name $PowershellGetModuleName).Version.ToString()) is imported" Write-Host -Object "$PackageManagementModuleName version: $((Get-Module -Name $PackageManagementModuleName).Version.ToString()) is imported" #endregion #region Powershell Module Repository Verification $Repositories = Get-PSRepository -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to get registered repository information" -ErrorAction Stop } # Checking if PSGallery repository is available if(-not ($Repositories.Name -match $PSGalleryRepositoryName) ) { Write-Host -Object "Adding $PSGalleryRepositoryName repository and setting it to trusted" Register-PSRepository -Name $PSGalleryRepositoryName -SourceLocation $PSGalleryRepositoryURL -PublishLocation $PSGalleryRepositoryURL -InstallationPolicy 'Trusted' -ErrorAction Continue -ErrorVariable oErr if($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to add $PSGalleryRepositoryName as trusted" Write-Error -Message "Failed to add $PSGalleryRepositoryName as trusted" -ErrorAction Stop } } else { Write-Host -Object "Trusting $PSGalleryRepositoryName repository" Set-PSRepository -Name $PSGalleryRepositoryName -InstallationPolicy 'Trusted' -ErrorAction Continue -ErrorVariable oErr if($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to set $PSGalleryRepositoryName as trusted" Write-Error -Message "Failed to set $PSGalleryRepositoryName as trusted" -ErrorAction Stop } } #endregion #Region Verify modules $ModulesToCheck = @() $ModulesAvailable = $true $ModuleTime = Measure-Command { foreach($ModuleName in $ModulesToImport) { $GalleryModuleInfo = Find-Module -Name $ModuleName -Repository PSGallery -ErrorAction SilentlyContinue $Module = Get-Module -Name $ModuleName -ListAvailable -ErrorAction SilentlyContinue if(-not $Module) { Write-Host -Object "##vso[task.logissue type=error;]$ModuleName is not installed on: $($env:computername)" Write-Error -Message "$ModuleName is not installed on: $($env:computername)" -ErrorAction Continue $Module = [pscustomobject]@{Version=[version]"0.0.0"} $ModulesAvailable = $false } $LocalModuleVersion = [version]($Module | Sort-Object -Descending -Property Version)[0].Version if($GalleryModuleInfo) { $ModulesToCheck += [pscustomobject]@{ModuleName = $ModuleName;Update= [version]($GalleryModuleInfo.Version) -gt $LocalModuleVersion;Version= $GalleryModuleInfo.Version.ToString();LocalVersion= $LocalModuleVersion.ToString()} } else { Write-Host -Object "##vso[task.logissue type=error;]Failed to retrieve module: $ModuleName from PSGallery" Write-Error -Message "Failed to retrieve module: $ModuleName from PSGallery" -ErrorAction Continue } } } Write-Host -Object "`nFetching versions of modules to use from PSGallery took: $($ModuleTime.Seconds) seconds`n" # Check that all modules are available if(-not $ModulesAvailable) { Write-Host -Object "Modules info:`n$($ModulesToCheck | Out-String)" Write-Error -Message "Not all needed modules are installed on: $($env:computername). Check previous errors" -ErrorAction Stop } if($ModulesToCheck -and $ModulesAvailable) { foreach($Module in $ModulesToCheck) { if($Module.Update) { Write-Host -Object "$($Module.ModuleName) has a newer version in PSGallery.`nCurrent: $($Module.LocalVersion)`nAvailable: $($Module.Version)" } else { Write-Host -Object "Latest version of module: $($Module.ModuleName) available locally on: $($env:computername). Version: $($Module.LocalVersion)" } Write-Host -Object "Importing module: $($Module.ModuleName)" Import-Module -Name $Module.ModuleName -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to import module: $($Module.ModuleName)" Write-Error -Message "Failed to import module: $($Module.ModuleName)" -ErrorAction Stop } else { Write-Host -Object "Successfully imported module: $($Module.ModuleName)" } Write-Host -Object "`n" } } else { Write-Host -Object "##vso[task.logissue type=error;]Failed to retrieve module information from PSGallery or modules are not installed" Write-Error -Message "Failed to retrieve module information from PSGallery or modules are not installed" -ErrorAction Stop } #endregion #region Test Assets Write-Host -Object "Input values for Pester Test Run:`nTestScripts: $TestScriptPath" foreach($Path in $TestPaths) { Write-Host -Object "Discovering assets to test in: $Path " } Write-Host -Object "TestResults: $TestOutPutFilePath" #endregion #Region Pester Tests Write-Host -Object "`nRunning Pester Tests:" $PesterContainers = $null if($TestPaths.Count -ge 1) { $PesterContainers = $TestPaths | ForEach-Object { Write-Host -Object "Creating pester container for path: $($_)" New-PesterContainer -Path $TestScriptPath -Data @{Path = $_; MinimumSeverityLevel = $MinimumSeverityLevel} } } else { Write-Host -Object "Creating pester container for path: $($TestPaths)" $PesterContainers = New-PesterContainer -Path $TestScriptPath -Data @{Path = $TestPaths; MinimumSeverityLevel = $MinimumSeverityLevel} } # $PesterConfig = [PesterConfiguration]::Default # $PesterConfig.TestResult.Enabled = $true # $PesterConfig.TestResult.OutputPath = $TestOutPutFilePath $Report = Invoke-Pester -Container $PesterContainers -Output Detailed -PassThru | ConvertTo-NUnitReport $Report.Save($TestOutPutFilePath) if(Test-Path -Path $TestOutPutFilePath) { Write-Host -Object "Test result successfully exported to file" # workaround for failed Pester test setting exit code 1 and failing pipeline if ($LASTEXITCODE -ne 0) { $LASTEXITCODE = 0 } } else { Write-Host -Object "##vso[task.logissue type=error;]Test results failed to be exported to file" Write-Error -Message "Test results failed to be exported to file" -ErrorAction Stop } #endregion } catch { if ($_.Exception.Message) { Write-Host -Object "##vso[task.logissue type=error;]$($_.Exception.Message)" Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Host -Object "##vso[task.logissue type=error;]$($_.Exception)" Write-Error -Message "$($_.Exception)" -ErrorAction Continue } exit 1 } finally { Write-Host -Object "Task ended at time: $(Get-Date -Format r)" } |
The report will look like the image below for a clean run.
The pipeline code to do this is show below.
The test script takes as an input the path to publish the result report and the built in test publish task takes the file and uploads to Azure DevOps.
The pester tests are maybe not the best when it comes to following Pester established structure, but they where written a long time ago, and only updated enough to work with version 5. The tests are split into different types of tests for how Powershell code/modules are structured.
Update: Have done some rewrites to the test to be more inline with good practice for Pester 5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [validateScript({Test-Path $_})] [string]$Path, [Parameter(Mandatory=$false)] [validateSet('Information', 'Warning','Error')] [string]$MinimumSeverityLevel = 'Error' ) BeforeDiscovery { #Get scripts/modules to be tested if ((Get-Item -Path $Path).PSIsContainer) { Write-Verbose "Specified path '$Path' is a directory" $scriptsModules = Get-ChildItem -Path $Path -Include *.psd1, *.psm1, *.ps1 -Recurse -File } else { Write-Verbose "Specified path '$Path' is a file" $scriptsModules = Get-Item -Path $Path -Include *.psd1, *.psm1, *.ps1 } $TestCandidates = $scriptsModules | Foreach-Object { switch -Wildcard ($_.Extension) { '*.psm1' { $ScriptType = 'Module' } '*.ps1' { $ScriptType = 'Script' } '*.psd1' { $ScriptType = 'Manifest' } } @{ FilePath = $_.FullName FileName = $_.Name ScriptType = $ScriptType } } } #region Powershell script Tests Describe "Powershell Script Validation Tests" { BeforeDiscovery { $TestCases = $TestCandidates | Where-Object {$_.ScriptType -eq "Script"} } Context 'Powershell File Tests' { It "Script: [<FileName>] should exist" -TestCases $TestCases { Param( $FilePath, $FileName, $ScriptType ) # Check that file exists $FileExists = Get-ChildItem -Path $FilePath -ErrorAction SilentlyContinue $FileExists | Should -Exist } } Context 'Powershell File Content Tests' { BeforeDiscovery { $astTestCases = $TestCases | ForEach-Object { $astTokens = $null $astErrors = $null $ast = [System.Management.Automation.Language.Parser]::ParseFile( $_.FilePath, [ref]$astTokens, [ref]$astErrors ) $astHash = @{ ast = $ast astToken = $astTokens astError = $astErrors FileName = $_.FileName } $astHash } } It "Script: [<FileName>] should not have parsing errors" -TestCases $TestCases { Param( $ast, $astToken, $astError, $FileName ) $astError | Should -BeNullOrEmpty } It "Script: [<FileName>] should have PARAM block" -TestCases $astTestCases { Param( $ast, $astToken, $astError, $FileName ) $Param = $ast.ParamBlock.Extent.Text {$Param} | Should -Not -Throw $Param | Should -Not -BeNullOrEmpty } It "Script: [<FileName>] should have SYNOPSIS" -TestCases $astTestCases { Param( $ast, $astToken, $astError, $FileName ) #$Comment = $astToken.where({$_.kind -eq 'comment' -and $_.Text -match ".SYNOPSIS"}) | Select-Object -ExpandProperty Text $Comment = $ast.GetHelpContent() {$Comment.SYNOPSIS} | Should -Not -Throw $Comment.SYNOPSIS | Should -Not -BeNullOrEmpty } It "Script: [<FileName>] should have DESCRIPTION" -TestCases $astTestCases { Param( $ast, $astToken, $astError, $FileName ) $Comment = $ast.GetHelpContent() {$Comment.DESCRIPTION} | Should -Not -Throw $Comment.DESCRIPTION | Should -Not -BeNullOrEmpty } It "Script: [<FileName>] should have PARAMETERS" -TestCases $astTestCases { Param( $ast, $astToken, $astError, $FileName ) $Comment = $ast.GetHelpContent() {$Comment.PARAMETERS} | Should -Not -Throw $Comment.PARAMETERS | Should -Not -BeNullOrEmpty } } } #endregion #region Module Tests Describe "Powershell Module Validation Tests" { BeforeDiscovery { # Get only modules for testing $TestCases = $TestCandidates | Where-Object {$_.ScriptType -eq "Module"} $astTestCases = $TestCases | ForEach-Object { $astTokens = $null $astErrors = $null $ast = [System.Management.Automation.Language.Parser]::ParseFile( $_.FilePath, [ref]$astTokens, [ref]$astErrors ) $astHash = @{ ast = $ast astToken = $astTokens astError = $astErrors FileName = $_.FileName } $astHash } } Context 'Module Files Tests' { It "Module: [<FileName>] should exist" -TestCases $TestCases { Param( $FilePath, $FileName, $ScriptType ) # Check that file exists $FileExists = Get-ChildItem -Path $FilePath -ErrorAction SilentlyContinue $FileExists | Should -Exist } It "Module: [<FileName>] should not have parsing errors" -TestCases $astTestCases { Param( $ast, $astToken, $astError, $FileName ) $astError | Should -BeNullOrEmpty } It "Module: [<FileName>] should import" -TestCases $TestCases { Param( $FilePath, $FileName, $ScriptType ) # Tests for modules { Import-Module -Name $FilePath -force } | Should -Not -Throw } } Context 'Module Content Tests' { BeforeDiscovery { $functionTestCases = $astTestCases | ForEach-Object { $func = $_.ast.FindAll({ param( [System.Management.Automation.Language.Ast]$ast ) $ast -is [System.Management.Automation.Language.FunctionDefinitionAst] -and # Class methods have a FunctionDefinitionAst under them as well, but we don't want them. ($PSVersionTable.PSVersion.Major -lt 5 -or $ast.Parent -isnot [System.Management.Automation.Language.FunctionMemberAst]) }, $true) $FileName = $_.FileName $funcHash = $func | ForEach-Object { @{ FileName = $FileName FunctionName = $_.Name FunctionHelp = $_.GetHelpContent() } } $funcHash } } It "Function: [<FunctionName>] in Module: [<FileName>] should have SYNOPSIS" -TestCases $functionTestCases { Param( $FileName, $FunctionName, $FunctionHelp ) {$FunctionHelp.SYNOPSIS} | Should -Not -Throw $FunctionHelp.SYNOPSIS | Should -Not -BeNullOrEmpty } It "Function: [<FunctionName>] in Module: [<FileName>] should have DESCRIPTION" -TestCases $functionTestCases { Param( $FileName, $FunctionName, $FunctionHelp ) {$FunctionHelp.DESCRIPTION} | Should -Not -Throw $FunctionHelp.DESCRIPTION | Should -Not -BeNullOrEmpty } It "Function: [<FunctionName>] in Module: [<FileName>] should have PARAMETERS" -TestCases $functionTestCases { Param( $FileName, $FunctionName, $FunctionHelp ) {$FunctionHelp.PARAMETERS} | Should -Not -Throw $FunctionHelp.PARAMETERS | Should -Not -BeNullOrEmpty } } } #endregion #region Module Manifest Tests Describe "Powershell Module Manifest Tests" { BeforeDiscovery { $TestCases = $TestCandidates | Where-Object {$_.ScriptType -eq "Manifest"} $Manifests = $TestCases | ForEach-Object { Test-ModuleManifest -Path $_.FilePath } $ManifestTestCases = $Manifests | ForEach-Object { @{ Name = $_.Name Guid = $_.Guid Version = $_.Version FileList = $_.FileList } } } Context 'Manifest Files Tests' { It "Manifest: [<FileName>] has a valid manifest" -TestCases $TestCases { Param( $FilePath, $FileName, $ScriptType ) { Test-ModuleManifest -Path $FilePath -ErrorAction Stop -WarningAction SilentlyContinue } | Should -Not -Throw } It "Manifest: [<Name>] has a guid" -TestCases $ManifestTestCases { Param( $Name, $Guid, $Version, $FileList ) $Guid | Should -Not -BeNullOrEmpty } It "Manifest: [<Name>] has a version" -TestCases $ManifestTestCases { Param( $Name, $Guid, $Version, $FileList ) $Version | Should -Not -BeNullOrEmpty } It "Manifest: [<Name>] has a list of files" -TestCases $ManifestTestCases { Param( $Name, $Guid, $Version, $FileList ) $FileList | Should -Not -BeNullOrEmpty } } } #endregion #region Powershell Script Analyzer Describe "PowerShell Script Analyzer Test" -Tag 'Compliance' { BeforeDiscovery { # Get unique path for scripts to use as input for script analyzer $ScriptPaths = Split-Path -Path $TestCandidates.FilePath | Sort-Object -Unique $Rules = Get-ScriptAnalyzerRule Switch ($MinimumSeverityLevel) { 'Information' {$Severities = @('Information', 'Warning', 'Error')} 'Warning' {$Severities = @('Warning', 'Error')} 'Error' {$Severities = @('Error')} } $PSScriptAnalyzerSettings = @{ Severity = $Severities ExcludeRule = @('PSUseSingularNouns') IncludeRule = $Rules } # Test all with PSScriptAnalyzer $ScriptAnalyzerResult = @() if( $ScriptPaths.Count -ge 1 ) { $ScriptAnalyzerResult = $ScriptPaths | ForEach-Object { Invoke-ScriptAnalyzer -Recurse -Path $_ @PSScriptAnalyzerSettings } } else { $ScriptAnalyzerResult = Invoke-ScriptAnalyzer -Recurse -Path $ScriptPaths @PSScriptAnalyzerSettings } $NoErrors = $null if($ScriptAnalyzerResult) { # Compare those not successful $NoErrors = Compare-Object -ReferenceObject $TestCandidates.FileName -DifferenceObject $ScriptAnalyzerResult.ScriptName | Where-Object { $_.SideIndicator -eq "<=" } | Select-Object -ExpandProperty InputObject $SkipPSATest = $false } else { # Everything was perfect, let's show that as well $NoErrors = $TestCases.FileName $SkipPSATest = $true } } Context 'Test Script Analyzer Violations for Scripts' { BeforeDiscovery { $TestCases = $ScriptAnalyzerResult | Where-Object { $_.ScriptName -like "*.ps1" } | Foreach-Object { @{ RuleName = $_.RuleName ScriptName = $_.ScriptName Message = $_.Message Severity = $_.Severity Line = $_.Line } } } It "[<ScriptName>] should not violate: [<RuleName>] on line: [<Line>] with severity: [<Severity>] and message: [<Message>]" -TestCases $TestCases -Skip:( $SkipPSATest ) { param( $RuleName, $ScriptName, $Message, $Severity, $Line ) $ScriptName | Should -Not -BeNullOrEmpty } } Context 'Test Script Analyzer Violations for Modules' { BeforeDiscovery { $TestCases = $ScriptAnalyzerResult | Where-Object { $_.ScriptName -notlike "*.ps1" } | Foreach-Object { @{ RuleName = $_.RuleName ScriptName = $_.ScriptName Message = $_.Message Severity = $_.Severity Line = $_.Line } } } It "[<ScriptName>] should not violate: [<RuleName>] on line: [<Line>] with severity: [<Severity>] and message: [<Message>]" -TestCases $TestCases -Skip:( $SkipPSATest ) { param( $RuleName, $ScriptName, $Message, $Severity, $Line ) $ScriptName | Should -Not -BeNullOrEmpty } } # Show good functions in the test, the more green the better Context 'Test Script Analyzer Passes' { BeforeDiscovery { $TestCase = $NoErrors | Foreach-Object { @{ ScriptName = $_ } } } It "[<ScriptName>] has no Script Analyzer Violations" -TestCases $TestCase { param( $ScriptName ) $ScriptName | Should -Not -BeNullOrEmpty } } } #endregion |
Lastly a sanitized version of the build pipeline in use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | name: $(BuildDefinitionName)-$(Build.SourceBranchName)-$(Date:yyyyMMdd)-$(Build.BuildId) pool: name: Azure Pipelines # Default hosted pipeline name vmImage: "windows-latest" variables: trigger: branches: include: - Dev - master paths: include: - "*" exclude: - "Azure-Automation-Runbook-CD.json" - "Deploy/Pipeline/*" - "Build/*" pr: none steps: - task: PowerShell@2 displayName: "Run Tests" inputs: targetType: filePath filePath: '$(System.DefaultWorkingDirectory)\Build\AzP-RunTests.ps1' arguments: '-TestScriptPath ''$(System.DefaultWorkingDirectory)\Build\Tests\*'' -TestPaths @("$(System.DefaultWorkingDirectory)\Runbooks","$(System.DefaultWorkingDirectory)\Modules") -TestOutPutFilePath ''$(System.DefaultWorkingDirectory)\Test-Pester.xml'' -MinimumSeverityLevel ''$(PSScriptAnalyzerErrorLevel)''' pwsh: true - task: PublishTestResults@2 displayName: "Publish Pester Test Results" inputs: testResultsFormat: NUnit failTaskOnFailedTests: true - pwsh: | $BranchName = "$(Build.SourceBranchName)" Write-Host -Object "Name of branch to trigger build: $BranchName" if($BranchName -eq "dev") { Write-Host -Object "Updating name of Runbook variable to use branch: $BranchName to DevGitFileDiff" Write-Host -Object "##vso[task.setvariable variable=GitDiffVariableName;]DevGitFileDiff" Write-Host -Object "Updating name of Module variable to use for branch: $BranchName to DevGitModuleDiff" Write-Host -Object "##vso[task.setvariable variable=GitDiffModuleVariableName;]DevGitModuleDiff" } name: "SetGitDiffVar" displayName: "Set GitDiffVariableName based on branch" - task: PowerShell@2 displayName: "Run Pipeline Helpers" inputs: targetType: filePath filePath: '$(System.DefaultWorkingDirectory)\Build\AzP-Helpers.ps1' arguments: "-VSteamAccount '$(VSteamAccount)' -VSteamProject '$(System.TeamProject)' -AccessToken '$(System.AccessToken)' -VariableGroupName '$(VariableGroupName)' -GitDiffVariableName '$(GitDiffVariableName)' -GitDiffModuleVariableName '$(GitDiffModuleVariableName)' -ForceDeployAll '$(ForceDeployAll)' -ArtifactRootPathName '$(ArtifactName)'" pwsh: true - task: PublishPipelineArtifact@1 displayName: "Publish AA resources as artifact" # Release CD will trigger even if no artifact is published # condition: and(succeeded(), ne(variables['GitFileDiff'], '!nochange!')) inputs: targetPath: '$(System.DefaultWorkingDirectory)\Deploy' artifactName: "$(ArtifactName)" |
For the actual runbook and modules code, the pipeline will only copy the ones that has changed since last trigger and put them in an artifact. This artifact is then used in the release part of the pipeline to publish to the different Azure Automation environments.
Hope the tests are usefull.
Happy tinkering!