ChefDK: install jdk using supermarket recipe

Let’s take a look at how we can utilise community recipes in your cookbooks. As an example, we install JDK on MacOS platform using a recipe from chef supermarket . For this, we are going to use 'java_se' cookbook (https://supermarket.chef.io/cookbooks/java_se).

The newest JDK version is 9, imagine the situation we need 8. Then we set 8 as constraint in metadata.rb and https://supermarket.chef.io/cookbooks/java_se/versions/8.162.0 will be used. Now our metadata.rb contains

 depends 'java_se', '~> 8.0'


Now we need to get our dependency:

 berks install

And upload it to chef-server:

 berks upload

My chef-server is not set up for ssl which results an error “SSL_connect returned=1 errno=0 state=SSLv3 read server certificate”. So I will use specific flag to ignore it:

 berks upload --ssl-verify 'false'


Next I am going to create a new recipe, let’s name it java.rbWhere I only need to specify

include_recipe 'java_se'

Having guards is a good practice, let’s add one here:

include_recipe 'java_se' unless jdk_installed?

where jdk_installed? can be implemented as

 def jdk_installed?
   !shell_out('which java | grep jdk').stdout.empty?
 end

Just one more last stroke is to set JAVA_HOME variable and to add it to PATH

 execute 'set_java_home' do
   command "echo 'export JAVA_HOME=' | tr -d '\n' >> #{bash_profile} &&
          /usr/libexec/java_home >> #{bash_profile} &&
          echo 'export PATH=$JAVA_HOME/bin:$PATH' >> #{bash_profile}"
 end

That’s simply it. Easy? Indeed, bon appetit!

Comments