Search code examples
rubychef-infrachef-recipelwrp

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?


Solution

  • 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