Chef: create a directory for a template if it doesn't already exist

Solution 1:

Use the directory resource to create the directory before creating the template. The trick is to also specify the recursive attribute otherwise the action will fail unless all parts of the directory but the last exist already.

config_dir = "#{node[:app][:deploy_to]}/#{node[:app][:name]}/shared/config"

directory config_dir do
  owner node[:user][:username]
  group node[:user][:username]
  recursive true
end

template "#{config_dir}/database.yml" do
  source "database.yml.erb"
  ...
end

Note that the owner and group of the directory resource are only applied to the leaf directory when it's being created. The permissions of the rest of the directory are undefined, but will probably be root.root and whatever your umask is.

Solution 2:

I'm not aware of any other way than using the directory resource before the template resource:

directory "#{node[:app][:deploy_to]}/#{node[:app][:name]}/shared/config/
  owner node[:user][:username]
  group node[:user][:username]
end