How can I make terminating and non-terminating PowerShell cmdlet errors cause lifecycle event hooks to fail in CodeDeploy?
Last updated: 2019-09-17
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?
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.
Important: The following resolution works with Windows PowerShell 5.1 and higher.
1. Run the $PSVersionTable command to find out what version of PowerShell you have, and then upgrade your version of PowerShell if necessary.
2. 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.