2

I'm currently using Chef to build out a cookbook that has to fire off a bunch of POST calls to this API and I have to capture the response in a variable to use it in a second HTTP call.

I've tried using the http_request resource from Ruby but I can only fire the call but don't know how to get the response captured:

http_request 'authorize' do   
action :post   
url '*****************************'   headers ({
        'Content-Type' => 'application/json'
        })   message ({
        :Username => "**********",
        :Password => "**********"
        }).to_json  
end

In another attempt, I tried using Chef's http client to fire off a POST call and a get a response:

  require "net/https"
  require "uri"
  require "json"
  uri = URI("******************************")
  req = Net::HTTP::Post.new(uri)
  req.set_form_data("Username" => "********", "Password" => "*********")

  res = Net::HTTP.start(uri.hostname, uri.port) do |http|
    http.request(req)
  end

  case res
  when Net::HTTPSuccess, Net::HTTPRedirection
    # OK
  else
    res.value
  end

But I keep getting this error when I run the chef-client on my node:

EOFError
--------
end of file reached

How can I send off a POST call using Chef/Ruby and capture its response?

ehjay
  • 21
  • 1
  • 2

2 Answers2

1

You want to use the Chef::HTTP client class, see https://coderanger.net/chef-tips/#4 for an example.

coderanger
  • 52,400
  • 4
  • 52
  • 75
  • Hi, would you be able to provide a more specific example on how to capture the response back? The response of my call returns two objects, APIKey, and ValidUntil, and I need to capture the APIKey value. my_id = Chef::HTTP.new('https://cmdb/').post('/') Would using this mean my_id will equal the response returned by my post call? – ehjay Feb 01 '17 at 15:41
  • Yep, you get back a string which is the body of the response. – coderanger Feb 01 '17 at 19:45
  • So i got the call to work and I get back the response as a text. Do you know how to get it back as an array so that I can parse out only ONE value in the response? For example if the response is { A: asdasda, B: asdasdasd} I'm only interested in getting the A value out – ehjay Feb 01 '17 at 21:25
  • GOT IT!! http://stackoverflow.com/questions/5410682/parsing-a-json-string-in-ruby – ehjay Feb 01 '17 at 21:40
0

In my case the request url had https so I had to add this line and it was working.

http.use_ssl = true

If you want a more generic approach that can handle both http and https see this answer -

https://stackoverflow.com/a/9227933/6226283

AnUp
  • 21
  • 1
  • 2