Locked

Deploy Apache vhost

Aug
1
2011

Deployment Ruby

I have been using the Ruby based deployment tool Capistrano for a while now to handle deployment of both for my Rails projects and also Java projects, and I really enjoy the power and simplicity that it provides.

One thing I was missing was a way to deploy Apache configuration files, which are usually changed frequently, to web servers insted of doing it manually. This is how I solved it:
# Interactions with the Apache server
namespace :apache do
task :deploy, :roles => :web do
# Overwrite the current configuration file with the one from Subversion
run "wget http:// subversion.my_host.com/my_vhost.conf \\
-O /etc/httpd/conf.d/my_vhost.conf"

# Change ServerName to the current server name
run "sed -i \'s/ServerName.*$/ServerName $CAPISTRANO:HOST$/g' \\
/etc/httpd/conf.d/my_vhost.conf"

apache.reload
end

[:stop, :start, :restart, :reload].each do |action]
task action, :roles => :web do
sudo "/etc/init.d/httpd #{action.to_s}"
end
end
end

To deploy the latest configuration file, just execute
cap apache:deploy

in your terminal.

Don't forget to assign your web server(s) the web role. For example
role :web, "web1.my_host.com", :no_release => true

The no_release attribute is used on other tasks that you do not want to be executed on your web server(s), such as deployment of application files. For example:
namespace :deploy do
task :check, :except => { :no_release => true } do
[...]

This solution can of course be developed further to handle different SCM paths for production (usually tags), test and development (usually the trunk) versions of the configuration file as well as handling multiple configuration files.

Observe that this solution will overwrite the current configuration file on the web server with the one from the SCM. Thus, you should not change the configuration file manually on the web server(s), but always checking in the change to your SCM and deploy it from Capistrano.

You could of course modify the solution to take a backup of the file, but as long as you always change the file by using Capistrano, there should no need for this. Besides, always having the latest configuration file in the SCM is generally a wise idea.