Chef create directories recursively with owner

11,116

Solution 1

Avoid String Interpolation

You own solution relies on string interpolation of different items, which you later again split into its pieces.

You can avoid this e.g. in the following way, while I don't completely understand, where these attributes are coming from:

[node['foo'], node['bar'], node['baz']].each do |path|
  directory path do
    owner 'testuser'
    group 'testuser'
   mode '0755'
  end
end

Avoid Declaring the Complete Path

A simpler way to create resources that recursively create directory resources for a complete path foo/baz/bar, you could use the following code, which splits the path into its pieces, without declaring the complete path in the manner of your question (%w{foo foo/bar foo/bar/baz}):

dir = "foo/bar/baz"
[].tap{|x| Pathname(dir).each_filename{|d| x << (x.empty? ? [d] : x.last + [d])}}.each do |dir|
  directory File.join(dir) do
    owner 'testuser'
    group 'testuser'
    mode '0755'
  end
end

Probably, there exists even a more elegant, shorter way to do it in Ruby.

Solution 2

if have default values in attributes like:

default["foo"]["logpath"] = "/var/log/apps"

then it be defined in recipe as to create directory :

directory node["foo"]["logpath"] do
  owner 'testuser'
  group 'testuser'
  recursive true
  mode '0755'
end
Share:
11,116
Gofrolist
Author by

Gofrolist

Updated on June 19, 2022

Comments

  • Gofrolist
    Gofrolist almost 2 years

    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?

  • Kris Robison
    Kris Robison over 6 years
    There is no reason to interpolate here. You're in ruby, so @StephenKing 's answer is correct.