chef-infrachef-recipechef-zero

Chef Custom Resource Guards


I have a custom resource (in a my cookbook's /resources folder in a file called dsc_class.rb). Basically, this is a way of invoking a DSC class resource easily without installing it and using the full DSC engine.

resource_name :dsc_class

default_action :create

property :file_name, kind_of: String, required: true, name_property: true

action :create do  
  powershell_script file_name do
    cwd ::File.dirname(file_name)
    code <<-EOH
    gc "#{file_name}" -Raw | iex
    $o = New-Object #{file_name.split('/').last.split('.').first}
    $o.Set()
    EOH
    not_if <<-EOH
    gc "#{file_name}" -Raw | iex
    $o = New-Object #{file_name.split('/').last.split('.').first}
    o.Test()
    EOH
  end
end

Works great - but action always "executes" so event when the resource guards and the powershell script doesn't execute, I get "x resources updated" in the log/output to the chef-client run.

How can I guard appropriately in my custom resource?

UPDATE: recipe contains

 dsc_class "/install/dsc/MyDscResource.ps1"

Solution

  • powershell_script is like all other execute-style resources, it always runs the command/script/whatever and relies on outer-level not_if or only_if clauses. In this case you would put those on the dsc_class resource instance in your recipe code.