Create multiple subfolders same time chef

1.7k Views Asked by At

Not sure how I would use the array to create multiple sub folders of the Sales folder in chef.

sales = 'Sales'
salesfolders = %w{'NewClients', 'MarketingMaterial', 'SalesTools', 'ClientInformation'}


directory "#{directory}\\#{salesfolders}"
  owner 'root'
  group 'root'
  mode '0755'
  recursive true
  action :create
end '

}

1

There are 1 best solutions below

0
On

OK – there's a few things to look at. Firstly, salesfolders isn't currently a valid array. You'll want to define it either like this:

salesfolders = ['foo', 'bar']

or like this:

salesfolders = %w(foo bar)

The latter syntax is shorthand for an array of strings – it's the same as the first example, but with less syntactic sugar.

Once you've got a nicely formatted array, you need to iterate through that array and run some code for every item in it. In Ruby, this is achieved by calling .each on an array, like so:

salesfolders.each do |salesfolder|
  # do something with salesfolder
end

Note that there's a salesfolder variable set there, which will be different for each item of the array – if we look at our previous example, the first time that block of code is run it will be foo, the second bar, and so on.

With that in mind, if we want to run your Chef code for each salesfolder, we can do something like this:

salesfolders.each do |salesfolder|
  directory "/something/else/here/#{salesfolder}" do
    owner 'root'
    group 'root'
    mode '0755'
    recursive true
    action :create
  end
end

For each salesfolder in our array, we'll run the directory block and create a new directory.