streetsoldier
streetsoldier

Reputation: 1319

Using File::read in a provider's default.rb in Chef

I am trying to create an LWRP that will call the resource that is defined within itself. My cookbook's structure is as follows:

enter image description here

In the machine cookbook's provider, I have a code snippet as follows:

require 'chef/provisioning'  # driver for creating machines
require '::File'

    def get_environment_json
      @@environment_template = JSON.parse(File::read(new_resource.template_path + "environment.json"))
      return @@environment_template
    end

The code is only trying to read a json file and I am using File::read for it.

I keep getting an error as follows:

LoadError

cannot load such file -- ::File

Does anyone know how I can use File::read inside my LWRP's provider?

Upvotes: 5

Views: 2156

Answers (3)

Tejay Cardon
Tejay Cardon

Reputation: 4223

OK, so the prior two answers are both half right. You have two problems. First, you can't require ::File as it's already part of Ruby. This is the cause of your error.

Second, if you call File.read you will grab Chef's File not ruby's. You need to do a ::File.read to use Ruby's File class.

Upvotes: 6

streetsoldier
streetsoldier

Reputation: 1319

It happens becuase Chef already has a file resource. We have to use the Ruby File class in a recipe.We use ::File to use the Ruby File class to fix this issue. For example:

execute 'apt-get-update' do
  command 'apt-get update'
  ignore_failure true
  only_if { apt_installed? }
  not_if { ::File.exist?('/var/lib/apt/periodic/update-success-stamp') }
end

Source: https://docs.chef.io/ruby.html#ruby-class

Upvotes: 0

DiegoSalazar
DiegoSalazar

Reputation: 13531

require '::File'

Is incorrect and is causing the LoadError. Delete this line. You don't need it. File is part of the Ruby core and doesn't need to be required.

To further explain, the string argument to require represents the file name of the library you want to load. So, it should look like require "file", or require "rack/utils".

Upvotes: 0

Related Questions