简体   繁体   中英

How can I access variables inside a not_if in chef

I'm new to chef so I might be doing something really wrong here. The question is, how do I access the LOG_DIR in the ruby block. I want to use LOG_DIR in quite a few places in my recipe.

LOG_DIR = "/var/log/cas"

ruby_block 'check logs' do
   block { ... }
   not_if do
      print(LOG_DIR)
      # The line above does not work.
      # NameError: uninitialized constant #<Class:#<Chef::Recipe:0x0000000003ac5f78>>::RESULT
      result = shell_out("ls #{LOG_DIR} | wc -l").stdout
      result == '0'
   end
end

The things that come to mind are to use node.run_state or/and use a lazy block. But I'm not sure how I would go about it or if it would achieve what I want.

A comment on if the lines below that have any problems would also be helpful. Thanks!

Using variables in not_if blocks is straightforward. But it should be for evaluation of true/false conditions. If the condition passed within not_if {.. } returns true or 0 then the Chef resource will be skipped.

Prevent a resource from executing when the condition returns true .

Another thing I would like to point out is that any variables starting with a capital letter in Ruby are constants . So first thing I would do is, have the variable as log_dir .

Also, instead of doing variable assignment ( result = ) inside the not_if block, I would do it outside. Or even better just directly create an expression that would evaluate to true or false .

Example:

log_dir = '/var/log/cas'

ruby_block 'check logs' do
  block do
    # some code
  end
  not_if { shell_out("ls #{log_dir} | wc -l").stdout.to_i == 0 }
end

Or in a more Ruby'ish way:

log_dir = '/var/log/cas'

ruby_block 'check logs' do
  block do
    # some code
  end
  not_if { Dir.empty?(log_dir) }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM