Skip to content

Instantly share code, notes, and snippets.

@scalp42
Created November 22, 2013 21:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save scalp42/7606857 to your computer and use it in GitHub Desktop.
Save scalp42/7606857 to your computer and use it in GitHub Desktop.
Figure if a resource exists or not in Chef before notifying it
resource_not_found = {}
begin
resources('ruby_block[my-resource-supposed-to-exist]')
rescue Chef::Exceptions::ResourceNotFound
resource_not_found['ruby_block[my-resource-supposed-to-exist]'] = true
end
template '/etc/my/template.conf' do
source 'template.conf.erb'
mode '640'
notifies :run, 'ruby_block[my-resource-supposed-to-exist]' unless resource_not_found['ruby_block[my-resource-supposed-to-exist]']
end
@whitehat101
Copy link

Inspired by your code, I wrote the following:

resource_exists = proc do |name|
  begin
    resources name
    true
  rescue Chef::Exceptions::ResourceNotFound
    false
  end
end

# Use:
template '/etc/my/template.conf' do
  source 'template.conf.erb'
  mode '640'
  notifies :run, 'ruby_block[my-resource-supposed-to-exist]' if resource_exists['ruby_block[my-resource-supposed-to-exist]']
end

I suspect that approaches like these aren't the most Chef ways to code this, but I'm not sure what would be a better solution. A library sounded like a good option, but then code is run in a different lexical scope, and that brought about more complexity, so I just used local variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment