dotnet-docker icon indicating copy to clipboard operation
dotnet-docker copied to clipboard

Avoid silent failures in Dockerfiles when executing PowerShell

Open mthalman opened this issue 2 years ago • 0 comments

Our Dockerfiles are authored to execute multi-statement PowerShell scripts with statement semi-colon separators. This allows for multiple statements to be executed in a single command line. The issue with this is that it doesn't handle error conditions like we would want. If one of the statements is executing a native command, not a PowerShell cmdlet, and that command fails, execution of the PowerShell script will continue. This is in spite of the $ErrorActionPreference variable which only applies to cmdlets and functions. The exit code of the native command would not to be explicitly checked to handle things correctly. An example of a native command that gets called like this is tar which may end up failing.

Note that PowerShell 7 has support for pipeline chain operators like && and || that do account for the exit code of native commands. However, we're often needing to execute PowerShell commands before PowerShell Core is even installed, so we are making use of the PowerShell 5 version installed in Windows Server Core.

Options for solving this:

  • Check the exit code appropriately when executing native commands.
  • Don't execute native commands in the context of PowerShell. This essentially would mean that we execute as much of the commands we need using CMD and only invoking PowerShell when necessary, limiting it to cmdlets only.
  • Use a multi-stage Dockerfile that executes these commands from a PowerShell 7 base stage that makes use oof the pipeline chain operators. This of course depends on the context of all cases where we need to execute PowerShell because it would require a scenario which only requires files to be copied from the PowerShell stage. This is admittedly complicating the Dockerfiles but is an available solution.

mthalman avatar Jul 25 '22 14:07 mthalman