Get the amount of memory in a node from inside a Chef recipe

Every time Chef runs on a node, it’ll reset Ohai’s special attributes (that’s those of the automatic type), and refill them with the new correct values.

This is what lets you see the stats of a node inside the management console or on the command line with knife.

But what if you have a particular recipe that you’d like to only run on machines with enough memory?

In this case it’s possible to get the Ohai attributes accessible in your recipe.

Once attributes are set again, they’re attached to the node object.

Where does Chef keep this stuff

After Chef runs ohai, the data is available as part of the node object. The amount of total memory is available in: node['memory']['total'].

How this data is formatted is depends on your operating system, so you may have to do a bit of checking if you have multiple OS types that you’re trying to apply this to.

Ohai gets this data in different ways depending on the operating system. Don’t worry: Ohai takes care of this for you. It detects the operating system and stores the data for you, so it’ll always be in the same place.

Even though it’s stored in the same place every time it’s not actually stored in the same way.

  • In Linux, which is a parse of /proc/meminfo, you’ll end up with the amount of memory in kilobytes with kB on the end.

  • For Windows, you’ll get the output of wmi with ‘kB’ attached.

  • For OSX, it’ll be the number of megabytes with ‘MB’ attached.

So if we want to have our recipe know the amount of memory in megabytes, we can do the following:

memory_in_megabytes = case node['os']
when /.*bsd/ / 1024 / 1024
when 'linux'[/\d*/].to_i / 1024
when 'darwin'[/\d*/].to_i
when 'windows', 'solaris', 'hpux', 'aix'[/\d*/].to_i / 1024

This way no matter how it’s stored, we’ll do the calculations needed and end up with an integer we can use later to determine if we should take an action or not.

if memory_in_megabytes > 512
  ## Do your thing!