Search code examples
rubychef-infra

Chef not_if/only_if command result and string comparison


I'm trying to run a command and compared its output but it appears my bellow code isn't working as I would expect it to.

execute 'testcond' do
  command "echo success"
  only_if {"lsb_release -rs" == '22.04'}
end

Solution

  • The guard you are using relies on the return status of the expression within { }. The expression you have is more like comparing two strings lsb_release -rs and 22.04. This evaluates to false, and as expected the execution is skipped.

    I'd recommend using node attribute that Chef collects about the node. Example:

    execute 'testcond' do
      command 'echo success'
      only_if { node['platform_version'] == '22.04' }
    end
    

    If you would like to use the command, we can get the result of the command in a variable, and then compare it within only_if guard.

    distro_ver = `lsb_release -rs`
    
    execute 'testcond' do
      command 'echo success'
      only_if { distro_ver.chomp! == '22.04' }
    end
    

    Note that I'd to use chomp as output of the command adds a newline (\n).