Search code examples
rubypowershellchef-infrachef-recipe

Chef NOT_IF and ONLY_IF validation issue in Windows recipes


Im runing this simple recipe block to create a web app in IIS

powershell_script "create_site_my_site" do
    code "New-webapppool -name 'My_Web_App'; New-Website -Name 'My_Web_App' -applicationpool 'My_Web_App' -Port '80' -IPAddress * -PhysicalPath 'c:\webs\My_Web_App'  "
    action :run
    not_if "get-website | where-object { $_.name -eq  'My_Web_App' }"
end

The problem here its that the NOT_IF part its allways True

PS C:\Users\carlos>
PS C:\Users\carlos> get-website | where-object { $_.name -eq 'asdfasdfasdf' }
PS C:\Users\carlos> echo $lastexitcode
1
PS C:\Users\carlos> get-website | where-object { $_.name -eq 'My_Web_App' }

Name        ID    State    Physical Path       Bindings
----        --    -----    -------------       --------
My_Web_App  6     Stopped  c:\webs\My_Web_App  http *:80:    
                                               https *:443:

PS C:\Users\carlos.camacho> echo $lastexitcode
1

Now, my question is about how to return True or False in the NOT_IF depending on my code return value ??


Solution

  • You should take advantage of the powershell_out resource from the windows cookbook.

    With that you may check the error of a command or not ot if the output is empty.

    In your case this should do:

    only_if powershell_out("get-website | where-object { $_.name -eq  'My_Web_App' }").stdout.empty?