Search code examples
rubyjsonchef-infracookbook

Read files in Chef without writing to the node


I am trying to read a file's contents and use it in my ruby code. In this step, I am not trying to do anything on the bootstrapped node. All I want to do is read a JSON file that will reside in cookbook's files folder and read the contents of the file and do something. I just want to use the value coming from JSON in my code itself. The code example is shown below. Any help is appreciated.

Attributes: default.rb

default["xyz"]["ohs_servers"]=[
  {"hostname"=> "intf301.linux.xyz.com","name" => "INTFIN_OHS_001", "short_name" => "OGS", "port" => "9931"},
  {"hostname"=> "intf302.linux.xyz.com","name" => "INTFIN_OHS_001", "short_name" => "OHS", "port" => "9931"}
]

Machines: machines.rb

require 'rubygems'
require 'json'
require 'pp'

json = File.read('environment.json')
obj = JSON.parse(json)

number = obj["name"]

x = node["xyz"]["ohs_servers"][number]["hostname"]

JSON file in cookbook's files folder: environment.json

{
  "template_name": "environment_template",
  "number": 0
}

Solution

  • use cookbook_file and then add run_action(:create)

    cookbook_file "myfile.txt" do
       path "somepathyouwantthefilebe/myfile.txt"
       source "myfile.txt"  #the name of the file in files folder of your cookbook"
    end.run_action(:create)  # read notes** bellow
    

    then you can have some ruby code to read from it for example

    File::read("somepathyouwantthefilebe/myfile.txt")
    

    ** the run action is nessecary since you are combining ruby code and resources in chef-zero