【问题标题】:Making a POST request with Chef向 Chef 发出 POST 请求
【发布时间】:2016-11-22 09:04:24
【问题描述】:

我需要使用带有 Chef 配方的 rest API 将 .json 文件发布到服务器,遵循 Chef's documentation 我想出了以下代码:

http_request '/tmp/bpp.json' do
  url 'http://localhost:8080/api/v1/blueprints/bpp'
  headers ({
    'AUTHORIZATION' => "Basic #{Base64.encode64(user)}",
    'CONTENT-TYPE' => 'aplication/json'
    })
  action :post
end

对于授权令牌,user 是一个包含'user:password' 的变量

当我运行这个厨师食谱时,我得到以下响应:

Error executing action `post` on resource 'http_request[POST /tmp/bpp.json]'

Net::HTTPServerException
------------------------
400 "Bad Request"

在此之前,我只是在执行 curl 调用,它工作正常,但我需要更改为 http_request 资源。这是旧的(工作)curl 请求:

curl --user user:password -H 'X-Requested-By:My-cookbook' --data @/tmp/bpp.json localhost:8080/api/v1/blueprints/bpp

我不太习惯使用 REST api,对我来说似乎是一个未知领域。

【问题讨论】:

    标签: ruby rest curl chef-infra chef-recipe


    【解决方案1】:

    你忘了message。使用文件名作为资源名不会将此文件作为数据发送。尝试添加:

    ...
    message lazy { IO.read('/tmp/bpp.json') }
    ...
    

    在您的情况下,只会发送资源名称 - /tmp/bpp.json。不是文件内容。如链接文档中所述:

    The message that is sent by the HTTP request. Default value: the name of the resource block See “Syntax” section above for more information.
    

    【讨论】:

    • 哦,我现在明白了,我发送的不是路径/tmp/bpp.json 中的文件,而是字符串/tmp/bpp.json 是否有一种优雅/简单的方法可以在这里将文件作为消息传递?是否应该(以任何方式)在主厨运行期间加载内存?
    • 视情况而定,您可以尝试在厨师运行期间读取文件(File.read)。但请记住纯 ruby​​ 代码是 executed on compile phase。因此,如果您想使用 chef 将此文件放在服务器上,则必须使用惰性块。您也可以将此文件放入数据包中。
    • 我把这个例子写得更具体了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 2016-05-30
    • 2011-11-08
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多