Opscode Chef Xtra: A Deletable Template via a Definition

While there is no delete action recognized by the Chef template resource, it is possible to fake it using a definition. For example, a definition for managing a configuration file for the multifaceted DNS server dnsmasq might look like the following:

define :dnsmasq_conf, :enable => true, :template => 'dnsmasq.conf.erb' do
	include_recipe 'dnsmasq'
 
	conffile = "/etc/dnsmasq.d/#{params[:name]}.conf"
 
	if params[:enable]
		template conffile do
			source params[:template]
			owner 'root'
			group 'root'
			mode 00644
			backup false
			notifies :restart, 'service[dnsmasq]', :delayed
		end
	end
 
	unless params[:enable]
		file conffile do
			action :delete
			notifies :restart, 'service[dnsmasq]', :delayed
			only_if {::File.exists?(conffile)}
		end
	end
end

The above definition follows the usual pattern of either being enabled or disabled. The former uses the expected template resource. The latter leans on the file resource to actually handle deletion of the template, taking care to do so only if the file actually exists first. Definitions allow one to combine resources in all kinds of interesting ways.

Post a Comment

Your email is never shared. Required fields are marked *

*
*