How to parse a json output from a rest curl command as an attribute value in the default.rb file
Use Case:
In the Chef recipe Attributes --> attributes.rb file has the following default attributes which will be consumed by my recipe and these values needs to be randomly generated using a curl command which outputs it in form of a json output
default['agent']['id'] = 'F73D3CA4-!#!#-653A-XXXX-BBBBBB'
default['agent']['token'] = '90F1C7EA-*()*-YYYY-2528-ZZZZZZ'
This value is used in the recipes --> act.rb Syntax used
tenant_id = node['agent']['id']
token = node['agent']['token']
The recipe makes use of the tenant_id and token in the following way in the recepie
dsa_args << " \"tenantID:#{tenant_id}\" \"tenantPassword:#{token}\""
The curl command to get the the id and token is:
curl --insecure -X GET -H "content-type: application/json" -H
"Accept: application/json" -d '{}'
https://XXX.XX.XXX.XX/rest/bat/rant/tenant?
name=Ante%20Data%20Wortyu%20Details
The Output is in the below format
{"id":"16","name":"Ante Data Wortyu Details","state":"ACTIVE", "tenantID":"F73D3CA4-!#!#-653A-XXXX-BBBBBB","tenantPassword":"90F1C7EA- () -YYYY-2528-ZZZZZZ"}
How would one pass the json formated output into my Chef Recipe or to the attributes file.
I went through the below link to get it completed but it fails with unauthorised errors:
https://www.twilio.com/blog/2015/10/4-ways-to-parse-a-json-api-with-ruby.html
Any help is greatly appreciated.
Thank you,
This is somewhat contrived and might not suit your entire use-case, but is an example of how you could parse the response body of an HTTP request as JSON and use it for Chef attributes.
# recipes/something.rb
require 'rest-client'
require 'json'
jsonResponse = JSON.parse(RestClient.get(URL))
node.override['agent']['id'] = jsonResponse["tenantID"]
node.override['agent']['token'] = jsonResponse["tenantPassword"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.