Wednesday, January 7, 2015

Curly Brackets in Chef/Ruby

Surprise, it helps to know the syntax of the language you are writing in.

The issue I ran into this time has to deal with the curly brackets in Ruby. 

Code Example 1
execute 'policy_selinux' do
  command "semodule -i /tmp/policy.pp"
  action :run
  not_if { 'semodule -l | grep policy' }
end

Code Example 2
execute 'policy_selinux' do
  command "semodule -i /tmp/policy.pp"
  action :run
  not_if 'semodule -l | grep policy' 
end

The key to note between example 1 and 2 is that in the second example there is no use of the curly "{}" brackets. This is for a very good reason. The curly brackets, in our case, are being used like a code block. This means that in example 1, the not_if is evaluating the {'semodule -l | grep policy'} as a code block. The code block evaluates as true all the time because it is evaluating a string that has no arguments to evaluate it(tautology). 

The code example 2 has no "{}" which means that the string is going to be used by the not_if statement. This will not be evaluated as a code block, but a string that is truly a command with a return status. This will allow us to get our return status like we desire.

Below is a good resource that helped lead me to my conclusion.
http://stackoverflow.com/questions/12565/what-do-the-different-brackets-in-ruby-mean 

No comments:

Post a Comment