Hugo Future Imperfect Slim

Dina Muscanell

Fierce. DevOps. Engineer

How to add conditional Ruby logic in the Test Kitchen file

Learn how to add ruby evaluations into the test kitchen file

2 minute read

Recently, version 0.15.0 of the kitchen-azurerm gem came out which featured a breaking change for our chef cookbooks. A change was introduced that allowed the user to pass in the name for the network interface card and changed the default name from nic to nic-<vm-name>. We needed to support either format.

Since we are running post deployment templates, the network interface name update impacted us. If you aren’t running any ARM templates or performing any additional network setup, the change will probably not impact your code base.

This should be a relatively simple fix, just find out what version of the gem is being used, then set the network interface name into a variable. It might also be worth while to know, we set the VM name as well.

In the .kitchen.yml one can add ruby by enclosing the code like <% ruby code goes here %>. Here is an example of some ruby code, along with the code to determine what version of the kitchen-azurerm gem the user is running.

<%
vm_name = 'vm-' + "#{SecureRandom.uuid}"[0,8]

nic = 'nic'
if Gem.loaded_specs["kitchen-azurerm"].version.release >= Gem::Version.new('0.15.0')
  nic = "nic-" + vm_name
end
%>
---

You might wonder why the --- is at the bottom of this block. It is important to leave that after the closing ruby %> for the rest of the file to achieve YAML syntax highlighting by your code editor of choice.

You can then use any variables set in the ruby blocks in your test kitchen YAML by again wrapping it in "<% ruby variable %>". It should work with or without the quotes. Here is an example of how to use the vm_name ruby variable (from the above code block) inside the YAML. vm_name: <%= vm_name %>

If you can code it in ruby, you can add it to your kitchen file and changes things based on the logic. This helps avoid having multiple kitchen files for the same driver.

On a closing note, another great switch we found was for the test results output. If test kitchen is running on a build agent, we want to set it as junit and send it to an XML file for Azure DevOps to pick up. In the ruby block:

<%
test_location = 'cli'

if ENV['username'] == "build-agent"
  test_location = "junit:./%{platform}_%{suite}_inspec.xml"
end
%>
---

In the kitchen logic, we have:

verifier:
  name: inspec
  reporter:
    - <%= test_location %>

Recent posts

See more

Categories

About

About