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

Last updated: 2022-02-03

My deployment lifecycle event hook in AWS CodeDeploy calls a Windows PowerShell cmdlet that returns errors. However, the cmdlet returns an exit code of 0 (success), and the deployment reports success. How do I make sure that both terminating and non-terminating PowerShell cmdlet errors cause my lifecycle event hooks to fail in CodeDeploy?

Short description

By default, PowerShell cmdlets run to completion and return an exit code of 0 unless an unrecoverable or terminating error occurs. CodeDeploy doesn't report a lifecycle event hook failure unless the associated script returns an exit code different than 0.

To make lifecycle event hooks fail when non-terminating errors occur, change the behavior of the script. To change the behavior of the script, configure the $ErrorActionPreference variable in the cmdlet to 'Stop'. PowerShell then stops the cmdlet from running and returns an exit code of 1 for both terminating and non-terminating errors.

For more information, see Understanding non-terminating errors in PowerShell on the Microsoft Scripting Blog.

Resolution

Important: The following resolution works with Windows PowerShell 5.1 and higher.

1.    Verify what Windows PowerShell version that you're using by running the following $PSVersionTable command:

$PSVersionTable

2.    If your version of Windows PowerShell is earlier than version 5.1, then upgrade your version of PowerShell. For instructions, see Download and install Windows PowerShell 5.1 on the Microsoft Docs website.

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

$ErrorActionPreference = 'Stop'

PowerShell now stops the cmdlet and returns an exit code of 1 for both terminating and non-terminating errors.