如何在 Chef 资源中使用变量 http_request

How to use variables in chef resource http_request

我正在使用厨师食谱中的 http_request 资源来发出需要代理用户和密码的 http 请求。我在替换属性中定义的变量或实际上替换任何变量时遇到问题 例如以下代码工作正常,其中用户名和密码是硬编码的。

http_request 'get-info' do
  url "http://host:8080/v123/orgs/abc"
  headers({ 'AUTHORIZATION' => "Basic #{ Base64.encode64('user1:pwd123')}",
    'Content-Type' => 'application/json'  }  )
  message ( "{ } " )
  action :get
end

但是如果我使用变量而不是像下面这样的硬编码凭据

u_name=node['mychef']['username']
pwd=node['mychef']['password']

http_request 'get-info' do
  url "http://host:8080/v123/orgs/abc"
  headers({ 'AUTHORIZATION' => "Basic #{ Base64.encode64('#{u_name}:#{pwd}')}",
    'Content-Type' => 'application/json'  }  )
  message ( "{ } " )
  action :get
end

然后我得到以下错误

    ================================================================================
    Error executing action `get` on resource 'http_request[get-info]'
    ================================================================================

    Net::HTTPServerException
    ------------------------
    401 "Unauthorized"

当然没有正确读取凭据。感谢有关如何替换 chef 资源中的变量的帮助 http_request。

同时我已经解决了我的问题。如果我像下面这样提前单独构建Base64编码,那么我可以很容易地替换http_request

中的值
sys_admin_creds = Base64.encode64("#{node['mychef']['username']}:#{node['mychef']['password']}")

然后我可以像下面这样替换值

headers({ 'AUTHORIZATION' => "Basic #{sys_admin_creds}",
    'Content-Type' => 'application/json'  }  )

我认为可能还有其他方法可以解决这个问题。当我直接替换 http_request 的 headers 中的值时,我认为引号和双引号的数量变得难以管理。但我相信这也可以解决。但现在我将继续我的解决方案。如果有人有更好的解决方案,仍然 post 它。所以我们总是可以改进我们的社区伙伴 :)。