Chef create directories recursively with owner

Viewed 11424

I need to create a tree of directories with owner "testuser". But if I'm specify "/foo/bar/baz" only "baz" created under "testuser", "/foo" and "/foo/bar" own to "root" user.

directory /foo/bar/baz do
  owner 'testuser'
  group 'testuser'
  recursive true
  action :create
  mode '0755'
end

Based on this documentation https://docs.chef.io/resource_directory.html we can use following structure and it's ok until I'm trying to use variables as directories.

%w[ /foo /foo/bar /foo/bar/baz ].each do |path|
  directory path do
    owner 'testuser'
    group 'testuser'
    mode '0755'
  end
end

If I specify variables in this list I've got directories with names "#{node[‘foo’]}" and so on.

%w[ #{node[‘foo’]} #{node[‘bar’]} #{node[‘baz’]} ].each do |path|
  directory path do
    owner 'testuser'
    group 'testuser'
    mode '0755'
  end
end

How to create a list of directories variables which will be expanded?

4 Answers

You do not need string interpolation. You're just working in straight ruby.

path = ''
path_ary = %w(foo bar baz) # or [node['foo'], node['bar'], node['baz'])
path_ary.each |path_element|
  path += "/#{path_element}"
  directory File.join(path) do
    owner 'testuser'
    group 'testuser'
    mode '0755'
  end
end
Related