October 8th, 2008

Deploying Static Websites With Net::SCP

4 comments on 402 words

I recently had a couple of projects that consisted of a few static HTML files and a couple images. I could have used a blog or lightweight CMS, but those were overkill. I could use scp, but remembering the scp command every time I made a small change proved to be a hassle. I could have used Capistrano, but that too, felt overboard for my simple needs. Lucky for me, in addition to Capistrano, Jamis Buck wrote Net::SCP which was the perfect tool for the job.

From the Net:SCP documentation:

”Net::SCP implements the SCP (Secure CoPy) client protocol, allowing Ruby programs to securely and programmatically transfer individual files or entire directory trees to and from remote servers. It provides support for multiple simultaneous SCP copies working in parallel over the same connection, as well as for synchronous, serial copies.”

The only thing we’re interested in is uploading, so lets get down to the code which I’ve packaged as a rake task.


REMOTE_DIR = "/home/caged/public/website.com/public"

desc 'Upload the site'
task :deploy do
  Net::SCP.start("hostname", "caged", :port => 3000) do |scp|
    scp.upload! 'site/index.html',  REMOTE_DIR
    scp.upload! 'site/stylesheets', REMOTE_DIR, :recursive => true
    scp.upload! 'site/images',      REMOTE_DIR, :recursive => true
    scp.upload! 'site/article',     REMOTE_DIR, :recursive => true
  end
end

Now lets take a look at the code. If you’re not using a public-key authentication, you’ll need to set :password in the start method. The upload! method is a synchronous (blocking) upload. If you’re uploading a lot of large files, you should consider using upload (no !) which will return immediately and continue processing your script while the upload is in progress. Finally, instead of specifying the name of every file inside a directory, you can set :recursive => true and Net::SCP will create the directory on the remote server and upload the files contained in it.

That’s it, the no-frills way to deploy a small static website.

Discussion

  1. Tim Harper Tim Harper said on October 8th

    Ever tried rsync?

  2. Justin Palmer Justin Palmer said on October 8th

    I would’ve probably used rsync if I had larger files because this approach recopies everything to the server.

  3. David Reese David Reese said on October 8th

    rsync was my first thought, too. it has the added advantage of being able to delete old files—you remove files and folders from local, they disappear on remote.

  4. Erik Kastner Erik Kastner said on October 10th

    I’m doing something similar, but with git. It’s harder up-front, but easier on-going.

    I set up a post-commit hook on the server that either does a ‘git reset—hard’ or, ‘cd <html-dir> && git pull’, then every time I push to that server, the live code is updated.

    It’s a poor man’s capistrano :)

Sorry, comments are closed for this article.