Thursday, February 23, 2017

Chef - Replace single line in a file

I had the need today to replace a single item in an INI file, but leave everything else as is.  This was not suitable for a template.  Did a quick loop, matched the string I wanted to replace, replaced the string and then re-wrote the modified file.  Here is what the Ruby code looks like:

ruby_block 'modify_line' do
 not_if "/opt/somefolder/etc/somefile.ini | grep \"replace_value = 1\""
 block do
  
  buildarray = []
  ischange = false
  lines = IO.readlines('/opt/somefolder/etc/somefile.ini')  
  for line in lines
   if (line.include? 'replace_value ')        buildarray << 'replace_value = 0'        ischange = true
   else
    buildarray << line
   end
  end
  
  if ischange
   writefile = File.open("/opt/somefolder/etc/somefile.ini", "w")   writefile.puts(buildarray)
   writefile.close
  end
  action :run
 end
end

No comments:

Post a Comment