Parse / extract server settings from your Capfile

One interesting thing that has evolved from our use of Capistrano is the configuration files have become the de-facto documentation hub for a project's server connection details. (We do maintain inventory data elsewhere, but for the developer in the trenches, config/deploy/prod.rb is the first place to look). A question arose: How to parse the settings out of these files?

Because they are in Ruby, the config files are actually little programs. They can't be parsed as such, only evaluated by the Ruby interpreter. Fortunately this is easy to do:

cap_info.rb

#!/usr/bin/env ruby
 
# run in a cap-managed project to get pertinent variable info
# output in YAML
 
require 'rubygems'
require 'capistrano/configuration'
require 'pp'
 
config = Capistrano::Configuration.new
config.load("Capfile")
config.logger.level = 1   # -v
 
for stage in config.stages do
  stage_config = Capistrano::Configuration.new
  stage_config.load("Capfile")
  stage_config.logger.level = 1   # -v
  stage_config.find_and_execute_task(stage)
  puts "#{stage}:"
  puts "  gateway: #{stage_config[:gateway]}"
  puts "  user: #{stage_config[:ssh_options][:user]}"
  puts "  deploy_to: #{stage_config[:deploy_to]}"
  puts "  roles:"
  for role in stage_config.roles do
    puts "    #{role[0]}:"
    for server in role[1].servers do
      puts "      - #{server}"
    end
  end
end

Output

prod:
  gateway: gateway.example.com
  user: deploy
  deploy_to: /var/www/sites/virtual/example
  roles:
    db:
      - web01
    web:
      - web01
      - web02
      - web03
      - web04

What now?

Cap gives you a rich set of tools. Even one-off tasks are easy to accomplish with cap shell, cap invoke, or by loading extra Ruby tasks with cap -f Capfile -f extra.rb. However, a common interchange format can be useful when integrating with non-Ruby tools.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>, <java>, <php>. The supported tag styles are: <foo>, [foo].
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Ready for transformation?