Parse/Edit Apache conf files with Ruby?

Solution 1:

I ended up just writing my own ruby script... Not very well done, but in case anyone needs it, here's the guts of it. It is looking for the contents of the <VirtualHost></VirtualHost> tag so that it can create a second <VirtualHost> with a ServerName which is a subdomain of our wildcard SSL cert...

begin
  logMsg "Updating apache config file for user #{user} (#{domain_httpd_conf})"

  domain_httpd_conf_io = File.open(domain_httpd_conf,File::RDONLY)

  ip_addr = ''
  main_vhost_config = []
  ssl_vhost_config = ["  ServerName #{auto_ssl_domain}",'  Include "conf/wildcard-ssl.conf"']

  indent = 1

  while line = domain_httpd_conf_io.gets

    line_indented = '  '*indent+line.strip

    if line =~ /^[[:space:]]*<VirtualHost ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(:[0-9]+)[^>]*>/
      ip = $1
    elsif line =~ /^[[:space:]]*<\/VirtualHost>/
      break 2
    elsif line =~ /^[[:space:]]*(ServerAlias|ServerName).*/
      main_vhost_config.push line_indented
    else

      if line =~ /^[[:space:]]*<[^\/]/
        indent += 1
      elsif line =~ /^[[:space:]]*<[\/]/
        indent = [1, indent-1].max
        line_indented = '  '*indent + line.strip
      end

      main_vhost_config.push line_indented
      ssl_vhost_config.push line_indented
    end
  end

  main_vhost_config.push "  Include #{extraconf_dir}/*.conf"

  domain_httpd_conf_io.close
  domain_httpd_conf_io = File.open(domain_httpd_conf,File::WRONLY||File::TRUNC)

  domain_httpd_conf_io.puts "<VirtualHost #{ip}:80 #{ip}:8080>"
  domain_httpd_conf_io.puts main_vhost_config
  domain_httpd_conf_io.puts "</VirtualHost>"

  domain_httpd_conf_io.puts

  domain_httpd_conf_io.puts "<VirtualHost #{ip}:443 #{ip}:8888>"
  domain_httpd_conf_io.puts ssl_vhost_config
  domain_httpd_conf_io.puts "</VirtualHost>"

rescue SystemCallError => err
  logErr "ERROR: Unexpected error: "+err

  domain_httpd_conf_io.close
end

Still has some bugs to work out but it mostly does what I want.