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

Complementary Process Diagnostic

With 30 minutes spent looking over your existing pipeline or process, we can diagnose the root cause(s) of slow releases or bugs. After 30 minutes on the phone or Skype with me, you will:

  1. Understand why your existing process may be allowing bugs to reach production and slow you down
  2. Learn ways you can increase the speed that features reach customers
  3. Have a list of ideas for improving your release process

We’ll have to move fast, of course, to get through all this in 30 minutes but don’t worry, I’ll keep us on track. To receive your meeting agenda and scheduling instructions, enter your email address below and click the button.