3

I want to include the Diplomat gem in my Chef cookbook so that I can perform Consul variable lookups in .erb templates.

I need to configure the 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

Set a variable as the URL path:

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

And finally, perform the lookup within the templates.

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

Where in the cookbook would I need to write the configuration code above such that I can perform variable lookups within .erb templates?

asdoylejr
  • 664
  • 1
  • 9
  • 20

2 Answers2

2

You want to use the chef_gem resource, but make sure to run it during the compile phase:

chef_gem 'diplomat' do
  action :nothing
  compile_time false
end.run_action(:install)
require 'diplomat'
coderanger
  • 52,400
  • 4
  • 52
  • 75
  • This saved my chef recipe as the system gems were not loaded by _require_. I had download the gem for chef specifically using the above command. Then use the below line to make it load `chef_gem "down"` `require 'down'` – Yugendran Jan 23 '19 at 18:52
  • 1
    @coderanger Thanks, but you say 'make sure to run it during the 'compile phase' but you have `compile_time false`. Is this a typo or have I misunderstood? – Jason Crease Jul 06 '20 at 11:32
0

Installing gems with Chef is relatively painless. Most of the time, you can use the gem_package resource, which behaves very similarly to the native package resource:

gem_package 'httparty'

You can even specify the gem version to install:

gem_package 'httparty' do version '0.12.0' end

You may have also seen the chef_gem resource. What's the difference?

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).

source: https://sethvargo.com/using-gems-with-chef/

iGallina
  • 590
  • 5
  • 11