Search code examples
chef-infra

Chef powershell_script guard throws false when throwing an exception


I have a chef powershell_script which seems to be running whenever the not_if guard throws an exception, I would like to change it so that the chef run fails when the not_if throws an exception, would that be possible?

Here's some really simplistic code, at the moment it seems to create the file, even though the guard is throwing an exception.

  powershell_script 'create file if no error' do
    code <<-EOH
      Write-Output 'File Created' | Out-File c:/users/vagrant/desktop/files.txt
    EOH
    not_if 'throw bad call'
  end

Thanks,
Alex


Solution

  • I wasn't able to find a good way to do this, so in order to make it work, I switched the call to be a ruby guard that's calling powershell_out as opposed to using the default powershell guard functionality.

      # This will stop the run because of the error thrown in the guard
      powershell_script 'create file if no error' do
        code <<-EOH
          Write-Output 'File Created' | Out-File c:/users/vagrant/desktop/files.txt
        EOH
        not_if { powershell_out!('throw bad call').stdout =~ /True/i }
      end
    

    This is useful in a use case where you're making a call to get some information from the network and that network is temporarily unavailable during the call

      # If blah.exe throws an exception, the run will be stopped
      # else, it will perform the normal register logic if blah.exe returns a not "true"
      powershell_script 'do_something_if_not_registered' do
        code <<-EOH
          &blah.exe register
        EOH
        not_if { powershell_out!('&blah.exe isRegistered').stdout =~ /True/i }
      end
    

    If anyone else finds/knows a better way to do this, please let me know.