How can I make terminating and non-terminating PowerShell cmdlet errors cause lifecycle event hooks to fail in CodeDeploy?

Last updated: 2019-04-19

My deployment lifecycle event hook in AWS CodeDeploy calls a Windows PowerShell cmdlet that returns errors while executing. However, the cmdlet returns an exit code of 0 (success), and the deployment reports success.

How can I be sure that both terminating and non-terminating PowerShell cmdlet errors will cause lifecycle event hooks to fail in CodeDeploy?

Short Description

By default, PowerShell cmdlets return an exit code of 0 unless an unrecoverable or terminating error occurs (for example, when dividing by 0). If a PowerShell cmdlet encounters an error that it can recover from (such as attempting to read a non-existent directory), the cmdlet still runs to completion and returns an exit code of 0. CodeDeploy, however, doesn't report a lifecycle event hook failure unless the associated script returns an exit code different than 0. For more information, see Understanding Non-Terminating Errors in PowerShell.

To make lifecycle event hooks fail when non-terminating errors happen, change the behavior of the script by configuring the $ErrorActionPreference variable.

Resolution

Include the following code at the beginning of your PowerShell cmdlet:

$ErrorActionPreference = 'Stop'

If you set $ErrorActionPreference to Stop, then PowerShell stops execution of the cmdlet and returns an exit code of 1 for both terminating and non-terminating errors.