Search code examples
powershellterraformterraform-cli

Powershell Profile to append parameters to a certain command


I have a certain command that I want to be able to append a parameter to as a powershell profile function. Though I'm not quite sure the best way to be able to capture each time this command is run, any insight would be helpful.

Command: terraform plan

Each time a plan is run I want to be able to check the parameters and see if -lock=true is passed in and if not then append -lock=false to it. Is there a suitable way to capture when this command is run, without just creating a whole new function that builds that command? So far the only way I've seen to capture commands is with Start-Transcript but that doesn't quite get me to where I need.


Solution

  • The simplest approach is to create a wrapper function that analyzes its arguments and adds -lock=false as needed before calling the terraform utility.

    function terraform {
      $passThruArgs = $args
      if (-not ($passThruArgs -match '^-lock=')) { $passThruArgs += '-lock=false'}
      & (Get-Command -Type Application terraform) $passThruArgs
    }
    

    The above uses the same name as the utility, effectively shadowing the latter, as is your intent.

    However, I would caution against using the same name for the wrapper function, as it can make it hard to understand what's going on.

    Also, if defined globally via $PROFILE or interactively, any unsuspecting code run in the same session will call the wrapper function, unless an explicit path or the shown Get-Command technique is used.