How do I get errors to propagate in the TeamCity P

2019-01-14 21:14发布

问题:

I have a TeamCity 7 Build Configuration which is pretty much only an invocation of a .ps1 script using various TeamCity Parameters.

I was hoping that might be a simple matter of setting:

  • Script

    File

  • Script File

    %system.teamcity.build.workingDir%/Script.ps1

  • Script execution mode

    Execute .ps1 script with "-File" argument

  • Script arguments

    %system.teamcity.build.workingDir% -OptionB %BuildConfigArgument% %BuildConfigArg2%

And then I would expect:

  • if I mess up my arguments and the script won't start, the Build fails
  • if my Script.ps1 script throws, the Build fails
  • If the script exits with a non-0 Error Level I want the Build to Fail (maybe this is not idiomatic PS error management - should a .ps1 only report success by the absence of exceptions?)

The question: It just doesn't work. How is it supposed to work? Is there something I'm doing drastically wrong that I can fix by choosing different options?

回答1:

As doc'd in the friendly TeamCity manual:

Setting Error Output to Error and adding build failure condition

In case syntax errors and exceptions are present, PowerShell writes them to stderr. To make TeamCity fail the build, set Error Output option to Error and add a build failure condition that will fail the build on any error output.

The keys to making this work is to change two defaults:

  1. At the top level in the Build Failure Conditions, switch on an error message is logged by build runner:
  2. In the [PowerShell] Build Step, Show advanced options and set Error output: Error

In 9.1 the following works (I wouldn't be surprised if it works for earlier versions too):

  1. create a PowerShell Build Step with the default options
  2. change the dropdown to say Script: Source code
  3. Add a trap { Write-Error "Exception $_" ; exit 98 } at the top of the script
  4. (Optional but more correct IMO for the kind of scripting that's appropriate for within TeamCity build scripts)

    Show advanced options and switch on Options: Add -NoProfile argument

  5. (Optional, but for me this should be the default as it renders more clearly as suggested by @Jamal Mavadat)

    Show advanced options and switch on Error output: Error

    (ASIDE @JetBrains: if the label was "Format stderr output as" it would be less misleading)

This covers the following cases:

  1. Parse errors [bubble up as exceptions and stop execution immediately]
  2. Exceptions [thrown directly or indirectly in your PS code show and trigger an exit code for TC to stop the build]
  3. An explicit exit n in the script propagates out to the build (and fails it if non-zero)


回答2:

There is an known bug in TeamCity that causes the behavior that the original poster noticed.

It is easy to work around, however.

At the end of your PowerShell script, add output indicating that the end of the script has been reached:

Echo "Packaging complete (end of script reached)"

Then, set up a new Build Failure Condition on your build to fail if the text you are echoing is NOT present in the output.



回答3:

You're over-thinking things. Try this:

  • Script

    File
    
  • Script File

    Script.ps1
    

    You don't need to give this a path - by default, it's relative to the checkout directory.

  • Script execution mode

    Put script into PowerShell stdin with "-Command -" arguments
    

This is exactly what I use to run a bunch of powershell scripts within Teamcity.

Update

I missed the bit in the original post about having failures in the powershell script fail the build. Apologies!

I've solved that part of the puzzle in two different ways.

For regular powershell scripts

Wrap the main code block in a try...catch; if an exception occurs, return a non-zero integer value. For successful execution, return 0.

This convention of returning zero for success dates back a very long way in history - it's used by Unix/Linux systems, DOS, CP/M and more.

For PSake build scripts

Use a wrapper powershell script to invoke psake and directly set the result of the teamcity build by writing a response message to stdout.

At the start of the script, define a status message that represents failure:

$global:buildResult = "#teamcity[buildStatus status='FAILURE' text='It died.']

Within the psake script, update $global:buildResult to indicate success in a dedicated task that's run last of all.

$global:buildResult = "#teamcity[buildStatus status='SUCCESS' text='It lives.']

At the end of the wrapper script, output the status message

write-host $global:buildResult

If anything in the build script fails, that last task won't run, and the default message (indicating failure) will be output.

Either way, Teamcity will pick up on the message and set the build status appropriately.



回答4:

If newer TeamCity versions are within your reach then it is worth checking out some of PowerShell build runner improvements.

In particular, changing Error Output from default warning to error may interest you.



回答5:

Just praise the lawd you don't need to work with Jenkins.. Can't use the PowerShell step for similar issues. Instead we need to use a "cmd" step that calls the following magic wrapper that will fail the step on exception and exit codes:

%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -Command "& { $ErrorActionPreference = 'Stop'; & 'path\to\script.ps1 -arg1 -arg2; EXIT $LASTEXITCODE }"


回答6:

An alternative to the accepted answer that works for me On TeamCity 9 (I don't like changing the 'Build Failure Conditions' option as it affects all build steps):-

I wanted PowerShell errors to fail the build step, but with a pretty message. So I wanted to throw an error message AND return an error code.... try / catch / finally to the rescue.

My demo script:

Try {
    Write-Host "Demoing the finally bit"
    # Make sure if anything goes wrong in the script we get an exception
    $ErrorActionPreference = "Stop"

    # This will fail and throw an exception (unless you add the file)
    Get-Content IDontExist.txt
}
Catch
{
    # Throwing like this gives a pretty error message in the build log
    throw $_
    # These give less pretty/helpful error messages
    # Write-Host $_
    # Write-Host $_.Exception.Message
}
Finally
{
    # 69 because it's more funny than 1
    exit(69)
}


回答7:

This has been superseded by options afforded by 9.x, but I'll leave it here as it definitely was bullet proof at the time and I couldn't find any other solution I liked better.


You could just do something that works. The following has been tested with

  • errors in the script bit
  • missing files
  • script exiting with non-0 ERRORLEVEL

In the TeamCity Powershell runner options, set it as follows:

  • Script File

    Source code

  • Script source

    $ErrorActionPreference='Stop'
    powershell -NoProfile "Invoke-Command -ScriptBlock { `$errorActionPreference='Stop'; %system.teamcity.build.workingDir%/Script.ps1 %system.teamcity.build.workingDir% --OptionB %BuildConfigArgument% %BuildConfigArg2%; exit `$LastExitCode }"

    (unwrapped version: powershell -NoProfile "Invoke-Command -ScriptBlock { $errorActionPreference='Stop'; %system.teamcity.build.workingDir%/Script.ps1 %system.teamcity.build.workingDir% --OptionB %BuildConfigArgument% %BuildConfigArg2%; exit$LastExitCode }"

  • Script execution mode

    Put script into PowerShell stdin with "-Command -" arguments

  • Additional command line parameters

    -NoProfile

I'm hoping against hope this isn't the best answer!



回答8:

Powershell v2 atleast had an issue with the -File option messing up error codes. There is some details about how it messes up and stuff.

The answer is either switch to -Command option and/or wrap it with a bat file that checks the LastErrorCode and returns 1+ if its supposed to fail.

http://zduck.com/2012/powershell-batch-files-exit-codes/



回答9:

Use something like this:

 echo "##teamcity[buildStatus status='FAILURE' text='Something went wrong while executing the script...']";

For reference, take a look on Reporting Build Status from Teamcity