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.

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/
  node.memory.total.to_i / 1024 / 1024
when 'linux'
  node.memory.total[/\d*/].to_i / 1024
when 'darwin'
  node.memory.total[/\d*/].to_i
when 'windows', 'solaris', 'hpux', 'aix'
  node.memory.total[/\d*/].to_i / 1024
end

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!
end

Liked what you saw? Get more automation insights delivered straight to your inbox.

indicates required