Require rest-client to module in Chef

714 Views Asked by At

I need to include res-client into my module in order to use RestClient::Resource.

I use the method in the module in a Chef recipe (ruby_block resource).

When my ruby_block resource tries to run the method in the module it output this error:

ERROR: cannot load such file -- rest-client

The following is my module residing in libraries folder:

module SecretServer
  def fetch_token
    payload = { :username => "***", :password => "***", :grant_type => "****"}
uri = ***
    request = RestClient::Resource.new(uri, :verify_ssl => false)
    post_request = request.post payload, :content_type => 'application/x-www-form-urlencoded'
    token = JSON.parse(post_request)["access_token"]
    return token
  end
end

require 'rest-client'
Chef::Recipe.include(SecretServer)
Chef::Resource.include(SecretServer)

The following is the resource that calls the function in module:

ruby_block 'parse data' do
  block do
   res = fetch_token
   puts res
   end 
end

This is just one of the several recipes in my cookbook. This recipe runs after the target node is almost ready and 'bundle install' has been run on the target node.

I also install rest-client in the target node. I tried each of following resource before my ruby_block resource:

chef_gem 'rest-client' do
  action :install
end

gem_package 'rest-client' do
  action :install
end

My question is how to include 'rest-client' and utilize it in Chef recipes?

1

There are 1 best solutions below

5
On

Long ago, the HTTP clients lived together in harmony. Then everything changed when the JSON gem attacked. Only the Chef::HTTP was still to be included with Chef as all the other clients were under too much flux to include.

We don't include that gem anymore, so to use it, you would have to install it yourself either via a cookbook gem dependency or a chef_gem resource. But for simple stuff you can just use our Chef::HTTP::SimpleJSON client instead:

Chef::HTTP::SimpleJson.new(uri).post("", args)["access_token"]

Or something like that (specifics depend on if you must use form encoding or if the server also speaks JSON).