1

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

  • What kind of error are you trying to check with `throw bad call`? We may not even need to use `powershell_script` with guard depending on the requirement. – seshadri_c Aug 28 '22 at 17:31
  • The not_if ends up making a http call to OctopusDeploy and asking if a node exists. My network is kinda flaky, so I think that the node is unable to connect to octopus and therefore throws an error and ends up returning false. I'm not 100% what happens next, but when that happens, I would just like execution to stop, so it doesn't accidently do something I don't want it to do. – Alexander Brehm Aug 29 '22 at 18:13
  • [This](https://stackoverflow.com/questions/14290397/how-do-you-abort-end-a-chef-run) seems to be related. You can try using standard Ruby error handling in the form of `begin`/`rescue`. – seshadri_c Aug 30 '22 at 02:31
  • As far as I can tell, the answer doesn't show how to get it so that an exception will stop the run from the powershell_guard clause. That being said, I found a workaround which is similar to the logic prescribed in your article. Thx – Alexander Brehm Aug 30 '22 at 18:12

1 Answers1

0

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.