17

If I have a template being created, how can I ensure that the directory exists? For instance:

template "#{node[:app][:deploy_to]}/#{node[:app][:name]}/shared/config/database.yml" do
  source 'database.yml.erb'
  owner node[:user][:username]
  group node[:user][:username]
  mode 0644
  variables({
    :environment => node[:app][:environment],
    :adapter => node[:database][:adapter],
    :database => node[:database][:name],
    :username => node[:database][:username],
    :password => node[:database][:password],
    :host => node[:database][:host]
  })
end

This fails since /var/www/example/shared/config does not exist for database.yml to be copied into. I'm thinking of how puppet allows you to "ensure" a directory exists.

19

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.

| improve this answer | |
  • That's why I dislike the recursive option ;-) – StephenKing Mar 12 '13 at 19:58
  • Yeah - me too. It just doesn't feel very Chef-y either having to specify each level or leave it all up to defaults. – Tim Potter Mar 12 '13 at 20:50
  • link broken new link for directory resource is this docs.chef.io/resource_directory.html – Immutable Brick Dec 13 '16 at 14:48
4

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.