skip to Main Content

I’m working on a chef recipe that will pull down a program installer depending on the memory total in a linux server. If the memory total is 8GB or more install …. if the memory is less than 8GB then install … . Does anybody happen to know how to script this?
Chef is ruby based.
Within my chef recipes I have attempted the following, but had no success.

puts "***** Linux server node['platform_family']=#{node['platform_family']}"
puts "***** Linux server node['memory.total']=#{node['memory.total']}"
# -------------------------------------------------------------------------------
puts "*****#{node['platform_family']}"
puts "*****#{node['memory.total']}"

if node['platform_family'] == 'debian' && node['memory.total'] >= 7000000
   remote_file '/tmp'
        source 'local file'
        action :create
   end
elsif
  remote_file '/tmp'
       source 'external file'
       action :create
  end

2

Answers


  1. If you’re only ever going to use this recipe in Linux, then this method will work:

    memory_in_megabytes = node.memory.total[/d*/].to_i / 1024
    
    if memory_in_megabytes > 512
      ## Do your thing!
    end
    

    Different OSes report this value differently and not always in the same format though. So if you want to support any system platform (just in case this has a use for someone not using Linux) this would be a far better option:

    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
    
    if memory_in_megabytes > 512
      ## Do your thing!
    end
    
    Login or Signup to reply.
  2. The remote_file resource can written in a better way (once) if we can compute the value of source property beforehand. Also since you have shown comparison of node['platform_family'], it appears you would need to match for OS families other than debian as well.

    Below code will match for platform_family and ['memory']['total'] and set a value that we can use with the source property.

    mem = node['memory']['total'][/d*/].to_i
    
    remote_src = case node['platform_family']
    when 'debian'
      mem >= 7000000 ? 'local file' : 'remote file'
    when 'redhat'
      mem >= 7000000 ? 'some file' : 'some other file'
    # when some other OS family if required
    end
    
    remote_file '/tmp/somefile' do
      source remote_src
      action :create
    end
    

    Note that I’m using ternary operator as an alternative to if / else within when condition of case statement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search