7n-zeg
Last Updated: September 09, 2019
·
1.991K
· justinlynn

Use value_for_platform to simplify selection logic

Typically when selecting, say, a package for installation the name of the package or packages differ from platform to platform and from version to version. Usually you'd have to use case statements or selection trees to decide which set of packages to install. Sadly this means that you've got a lot of repetitive and, usually, hard to read and understand logic in your recipes. Enter the built-in helper valueforplatform. The valueforplatform helper takes a data structure (effectively, a hash of hashes) and returns a value which represents the value for the platform on which the recipe is being executed.

Example:

values = {
  :ubuntu => {
    ["11.10","12.04","12.10"] => "smv_ubuntu_new",
    "11.04" => "smv_ubuntu_legacy",
    :default => "smv_ubuntu_default"
  },
  [:centos, :redhat] => {
    :default => "smv_redhat_default"
  },
  :default => "smv_default"
}

value = value_for_platform(values)

This code when evaluated on an Ubuntu 12.04 system returns "smvubuntunew", on an Ubuntu 11.04 system it will return "smvubuntulegacy", and when evaluated on an Ubuntu 9.10 system it will return "smvubuntudefault". When evaluated on any centos or redhat system it will return "smvredhatdefault". When evaluated on say debian, it will return "smv_default" and so on.

The values may be any ruby object, as valueforplatform is simply encapsulated selection logic so that your recipes don't need to couple to node attribute structures.

See http://wiki.opscode.com/display/chef/Recipes#Recipes-valueforplatform for more in-depth information.

1 Response
Add your response

3503

Hey Justin! I use this myself a lot. One thing really hit me hard: value_for_platform fails silently when used in an attribute file. Afaik this will change in chef 11.

over 1 year ago ·