Skip to content

Instantly share code, notes, and snippets.

@alastairtree
Created June 28, 2020 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alastairtree/b7c6532a8ca915fc303e39867dc81b83 to your computer and use it in GitHub Desktop.
Save alastairtree/b7c6532a8ca915fc303e39867dc81b83 to your computer and use it in GitHub Desktop.
Quick integration tests of terraform modules using powershell
Function TC-Escape ([string] $text){
return $text.Replace("|","||").Replace("'","|'").Replace("\n","|n").Replace("\r","|r").Replace("[","|[").Replace("]","|}")
}
Function Invoke-Exec
{
[CmdletBinding()] param([Parameter(Position=0,Mandatory=1)][scriptblock]$cmd)
$scriptExpanded = $ExecutionContext.InvokeCommand.ExpandString($cmd).Trim()
Write-Host "Executing command: $scriptExpanded"
& $cmd
if ($lastexitcode -ne 0) {
throw ("Invoke-Exec failed with exit code '$lastexitcode' executing command " + $scriptExpanded)
}
}
Function Invoke-TerraformModuleTests {
# parameters
$TestScriptName = "main.tf"
$modulesTestPath = "$PSScriptRoot\modules\*\test\"
$passed = 0; $failed = 0;
$IsTeamcity = If(Test-Path env:\TEAMCITY_VERSION) { $true } Else { $false }
# Recurse through all child folders to find all the tests and execute each one as a seperate team city test
Get-ChildItem $modulesTestPath -Filter $TestScriptName -Recurse |
Foreach-Object {
$testName = ($_.FullName | Resolve-Path -Relative).Trim(".","\").Replace("\$TestScriptName", "").Replace("\"," - ")
$folder = Split-Path $_.FullName -Parent
if($IsTeamcity){
Write-Host "##teamcity[testStarted name='$testName' captureStandardOutput='true']"
}
$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
try{
Push-Location $folder
Invoke-Exec { terraform init }
Invoke-Exec { terraform plan }
Write-Host "Test passed: $testName" -foregroundcolor "green"
$passed++
}
catch {
Write-Host "Test failed: $($_.Exception)" -foregroundcolor "red"
if($IsTeamcity){
Write-Host "##teamcity[testFailed name='$(TC-Escape($testName))' message='$(TC-Escape($_.Exception.Message))']" -foregroundcolor "red"
}
$failed++
}
finally{
$elapsed.Stop()
if($IsTeamcity){
Write-Host "##teamcity[testFinished name='$(TC-Escape($testName))' duration='$($elapsed.ElapsedMilliseconds)']" -foregroundcolor "green"
}
Pop-Location
}
}
$color = if($failed -eq 0) {"green"} else {"red"}
Write-Host "Test complete $passed passed and $failed failed" -foregroundcolor $color
}
Invoke-TerraformModuleTests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment