Execute instructions in chef recipes only for Test Kitchen converge action

450 views Asked by At

I need a way to run parts of chef recipes only in case of converge action in Test Kitchen.

I found a way to do it for ChefSpec:

unless defined?(ChefSpec)
  
  cookbook_file "/home/#{node['user']}/script.sh" do
    source 'install.sh'
    owner node['user']
    mode '0755'
    action :create
  end

end

How I can do it for Kitchen tool?

1

There are 1 answers

0
seshadri_c On

This requirement has been discussed in detail on a feature request on Github.

There are two ways to do this. One is to define an environment variable such as TEST_KITCHEN, then use it in recipe with if condition, only_if or not_if guards.

Below should work:

Set the environment variable:

export TEST_KITCHEN="1"

Run the resource conditionally:

if ENV['TEST_KITCHEN']
  cookbook_file "/home/#{node['user']}/script.sh" do
    source 'install.sh'
    owner node['user']
    mode '0755'
    action :create
  end
end

Other way is to use a node attribute, something like node['test_kitchen'] set to true and use it to run actions conditionally.

  cookbook_file "/home/#{node['user']}/script.sh" do
    source 'install.sh'
    owner node['user']
    mode '0755'
    action :create
    only_if { node['test_kitchen'] }
  end