Reputation: 5586
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!
Upvotes: 1
Views: 1511
Reputation: 15784
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
Upvotes: 2
Reputation: 37600
Ohai already provides you an automatic attribute for the python version. You can access it as follows:
node['languages']['python']['version']
The corresponding code is here.
The resulting code could look as follows:
if node['languages']['python']['version'].to_f < 3
package "package_a"
else
package "package_b"
end
Upvotes: 1