I need to write some scripts to make changes to Apache conf files, namely to add/update VirtualHosts. I plan on doing this in Ruby. before I write my own, are there any scripts/rubygems which allow Ruby to parse/modify Apache conf files, specifically <VirtualHost> directives?

  • Not sure if StackOverflow would be a better place. Let's try ServerFault first and see what happens :-) – Josh Mar 12 '10 at 19:50

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...

  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

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

      main_vhost_config.push line_indented
      ssl_vhost_config.push line_indented

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

  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 "<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


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


No clue, but one thing that may help you is apache's support for mass virtual hosting: http://httpd.apache.org/docs/2.2/vhosts/mass.html

If you can enforce consistency across your vhosts then maybe you don't need ruby to create/manage/edit them. Convention over configuration is the rails way right?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.