Trying to understand this recipe

I'm new to CHEF and I'm starting to learn to read/write recipes. I'm trying to understand the consul recipe (https://github.com/johnbellone/consul-cookbook/blob/master/recipes/default.rb).

I can follow most of the recipe, but the part that has me confused are lines 46-55:

config = consul_config service_name do |r|
node['consul']['config'].each_pair { |k, v| r.send(k, v) }
notifies :reload, "consul_service[#{service_name}]", :delayed
end

install = consul_installation node['consul']['version'] do |r|
if node['consul']['installation']
node['consul']['installation'].each_pair { |k, v| r.send(k, v) }
end
end

Can anyone explain to me what those lines are saying?

In this line config = consul_config service_name do |r|

config is a variable assignment

consul_config is a custom resource (AKA LWRP, HWRP) See libraries/consul_config.rb

service_name is a variable that points to node[‘consul’][‘service_name’] See default.rb line 36

do is a keyword in ruby to create an interator

|r| is the iterator assignment.

node['consul']['config'].each_pair { |k, v| r.send(k, v) }

node[consul][config] points to the attribute (which in this case happens to be a hash/mash

.each_pair is the ruby sytnax for itterating

{ |k,v| r.send(k,v) } has 2 iterators k & v which are assigned the value from node[consul][config]
For every key value pair that is itterated over, it copies those key value pairs to the iterator |r|

notifies :reload, "consul_service[#{service_name}]", :delayed restarts the service

So basically it is taking all the key value pairs from node[consul][config] and is duplicating them to custom resources.

So if you have

"consul": {
  "config": {
    "foo": 42,
    "bar":9000
  }
}

It will turn “foo” into a custom resource and “bar” into a custom resource.

Custom resources are a little more advanced. Previously they were also called Light weight resources LWRP and Heavy Weight resources HWRP.

https://docs.chef.io/custom_resources.html

1 Like

Wow - thank you for the thorough explanation!