Method: Chef::Role.from_disk

Defined in:
lib/chef/role.rb

.from_disk(name) ⇒ Object

Load a role from disk - prefers to load the JSON, but will happily load the raw rb files as well. Can search within directories in the role_path.



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/chef/role.rb', line 247

def self.from_disk(name)
  paths = Array(Chef::Config[:role_path])
  paths.each do |path|
    roles_files = Dir.glob(File.join(Chef::Util::PathHelper.escape_glob_dir(path), "**", "**"))
    js_files = roles_files.select { |file| file.match(%r{/#{name}\.json$}) }
    rb_files = roles_files.select { |file| file.match(%r{/#{name}\.rb$}) }
    if js_files.count > 1 || rb_files.count > 1
      raise Chef::Exceptions::DuplicateRole, "Multiple roles of same type found named #{name}"
    end

    js_path, rb_path = js_files.first, rb_files.first

    if js_path && File.exist?(js_path)
      # from_json returns object.class => json_class in the JSON.
      hsh = Chef::JSONCompat.parse(IO.read(js_path))
      return from_hash(hsh)
    elsif rb_path && File.exist?(rb_path)
      role = Chef::Role.new
      role.name(name)
      role.from_file(rb_path)
      return role
    end
  end

  raise Chef::Exceptions::RoleNotFound, "Role '#{name}' could not be loaded from disk"
end