ccamacho
ccamacho

Reputation: 729

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 ??

Upvotes: 2

Views: 6356

Answers (3)

Mike Robinet
Mike Robinet

Reputation: 843

powershell_script "create_site_my_site" do
    guard_interpreter :powershell_script
    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

You need to specify guard_interpreter :powershell_script. Be aware of CHEF-1943 and make sure guard_interpreter is before the guard and do not put the guard in a block.

powershell_script documentation

An excellent reference on the Chef powershell provider is this video.

Simply using the IIS cookbook is another option.

Upvotes: 5

arco444
arco444

Reputation: 22821

I think this is because you're not telling the not_if guard to use the powershell_script interperter.

Does this work?

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' }).count -gt 0"
    guard_interpreter :powershell_script
end

Upvotes: 1

Tensibai
Tensibai

Reputation: 15784

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?

Upvotes: 2

Related Questions