lmtx lmtx - 2 months ago 12
Ruby Question

Check version of Python from Chef CookBook and install package according to the outcome

I need to write a Chef CookBook that will install some packages according to the version of Python installed in the system.

Is it possible to have following logic in Chef recipe:

python_version = `python -V` # check python version
if python_version == '2.6.6'
package 'package_a' # install package_a using Chef package resource
elsif python_version == '3.3.5'
package 'package_b' # install package_b using Chef package resource
else
break # stop execution of cookbook
end


Thank you in advance!

Answer

Short answer yes.

You should use shell_out!('python -V').stdout().chomp() instead of the backticks.

BUT the information already exist in node automatic attributes so you don't have to call python -V:

ohai languages return:

{
  "python": {
    "version": "2.7.3",
    "builddate": "Jun 22 2015, 19:33:41"
  },
  "perl": {
    "version": "5.14.2",
    "archname": "x86_64-linux-gnu-thread-multi"
  },
  "c": {
    "gcc": {
      "version": "4.6.3",
      "description": "gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) "
    }
  }
}

So you should be able to write in your recipe:

python_version = node['languages']['python']['version']
if python_version == '2.6.6'
  package 'package_a'           # install package_a using Chef package resource
elsif python_version == '3.3.5'
  package 'package_b'           # install package_b using Chef package resource
else
  raise                         # stop execution of cookbook
end

To stop a chef run, you need to use raise by the documentation

Comments