如何在 Chef 食谱中包含和配置 ruby 库?

How would I include and configure a ruby library in a Chef recipe?

我想将 Diplomat gem 包含在我的 Chef 食谱中,以便我可以在 .erb 模板中执行 Consul 变量查找。

我需要配置 Consul URL:

irb(main):015:0> require 'diplomat'
irb(main):016:0> Diplomat.configure do |config|
irb(main):017:1*   config.url = "consulurl:80"
irb(main):018:1> end

将变量设置为 URL 路径:

irb(main):020:0> kv_path = "path/to/variable"
=> "path/to/variable"

最后,在模板中执行查找。

irb(main):022:0> foo = Diplomat::Kv.get(kv_path + '/test_foo_123')
=> "bar"

我需要在食谱中的什么地方编写上面的配置代码,以便我可以在 .erb 模板中执行变量查找?

使用 Chef 安装 gems 相对轻松。大多数时候,您可以使用 gem_package 资源,它的行为与本机包资源非常相似:

gem_package 'httparty'

您甚至可以指定要安装的 gem 版本:

gem_package 'httparty' do version '0.12.0' end

您可能还看到了 chef_gem 资源。有什么区别?

The chef_gem and gem_package resources are both used to install Ruby gems. For any machine on which the chef-client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to the chef-client. Use the chef_gem resource to install gems into the instance of Ruby that is dedicated to the chef-client. Use the gem_package resource to install all other gems (i.e. install gems system-wide).

来源:https://sethvargo.com/using-gems-with-chef/

您想使用 chef_gem 资源,但请确保在编译阶段 运行 它:

chef_gem 'diplomat' do
  action :nothing
  compile_time false
end.run_action(:install)
require 'diplomat'