Skip to content

Instantly share code, notes, and snippets.

@stevendanna
Created October 11, 2011 16:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevendanna/1278614 to your computer and use it in GitHub Desktop.
Save stevendanna/1278614 to your computer and use it in GitHub Desktop.
Monkey patching the Template resource to do validation
#
# Cookbook Name:: template_checker
# Recipe:: default
#
# Copyright 2011, Opscode, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
template "/tmp/validation_test.txt" do
source "temp.erb"
verify_template {|template_path|
# The block is passed the temporary path of the rendered
# template
Chef::Log.info "Testing #{template_path}"
# Do some test here, return true if it passes, false if it fails
true
}
end
#An example of how you might run a shell command as your test
template "/tmp/validation_test.txt" do
source "temp.erb"
verify_template {|template_path|
Chef::Log.info "Testing #{template_path}"
# Run a command and test its return value
`some_command #{template_path}`
$? == 0
}
end
# This is a library file. Place in libraries/
class Chef::Resource::Template < Chef::Resource::File
def verify_template(&block)
if block_given? and block
@block=block
else
@block
end
end
end
class Chef::Provider::Template < Chef::Provider::File
def action_create
render_with_context(template_location) do |rendered_template|
rendered(rendered_template)
if ::File.exist?(@new_resource.path) && content_matches?
Chef::Log.debug("#{@new_resource} content has not changed.")
set_all_access_controls(@new_resource.path)
else
check_template(rendered_template) if @new_resource.verify_template
backup
set_all_access_controls(rendered_template.path)
FileUtils.mv(rendered_template.path, @new_resource.path)
Chef::Log.info("#{@new_resource} updated content")
@new_resource.updated_by_last_action(true)
end
end
end
def check_template(rendered_template)
unless @new_resource.verify_template.call(rendered_template.path)
raise Chef::Exceptions::ValidationFailed, "Could not validate rendered template #{rendered_template.path}"
end
end
end
@stevendanna
Copy link
Author

Users of this should note that this monkey patch is not compatible with why-run mode and was written against an older version of Chef.

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