简体   繁体   English

如何将json数据解析为厨师食谱属性

[英]how to Parse json data into a chef recipe attributes

How to parse a json output from a rest curl command as an attribute value in the default.rb file 如何将rest curl命令的json输出解析为default.rb文件中的属性值

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 在Chef配方属性-> attribute.rb文件中,具有以下默认属性,这些默认属性将由我的配方使用,并且这些值需要使用curl命令以json输出的形式输出的随机生成

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 在配方中使用此值-> act.rb使用的语法

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 在食谱中,食谱通过以下方式使用tenant_id和令牌

dsa_args << " \"tenantID:#{tenant_id}\" \"tenantPassword:#{token}\""

The curl command to get the the id and token is: curl用来获取ID和令牌的命令是:

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"} {“ 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. 如何将json格式的输出传递到我的Chef Recipe或属性文件中。

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 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. 这在某种程度上是人为设计的,可能不适合您的整个用例,但这是如何将HTTP请求的响应主体解析为JSON并将其用于Chef属性的示例。

# 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"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM