whoami

Lucas Jenß

cat /etc/motd

The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.

Close-up of white dominoes with black dots standing on green felt surface, shallow depth of field, focused mood

ls -la ~/languages/

total 8
drwxr-xr-x
▶ PHP
▶ Ruby
▶ Scala
▶ C#
▶ JavaScript
▶ Objective-C
▶ Shell Scripting

ls -la ~/toolchain/

total 7
drwxr-xr-x
▶ Typo3
▶ Akka
▶ Capistrano
▶ Git
▶ MAMP
▶ Adobe Illustrator
▶ NSTrackingArea (Cocoa)

uname -a

platforms
drwxr-xr-x
▶ Mac OS X
▶ Unix

Updating Capistrano stages automatically from YAML

Capistrano stage definitions drift when servers change and deployment files stay untouched. This journal entry covers writing a Ruby script that automatically updates Capistrano stages from YAML while keeping output reviewable and rejecting invalid host data before writes.

The workflow uses one checked-in YAML file as source of truth, renders the Ruby files Capistrano expects, and removes obsolete generated stages. Standard-library Ruby, atomic replacement, a dry-run mode and no embedded secrets keep it practical for an Australian product team or a larger release pipeline. Developers can inspect the generated Ruby without learning a new configuration format, while release managers get a compact topology diff.

Designing a YAML source of truth

Keep topology separate from deployment behaviour. Put stage names, hosts, users, roles, ports and primary status in YAML; leave shared tasks, hooks and environment variables in deploy.rb. Stage files should say where code runs, not hold passwords.

version: 1
stages:
  staging:
    servers:
      - host: app-staging.customer.com.au
        user: deploy
        roles: [app, web]
        primary: true
        port: 22
  production:
    servers:
      - host: app-production.customer.com.au
        user: deploy
        roles: [app, web]
        primary: true

Roles map directly to Capistrano roles such as :app and :web. A primary server receives release tasks first, while extra servers remain in the same role. One server per list item makes additions and removals explicit in Git, giving release managers a useful review without exposing unrelated configuration.

For an Australian customer, app-staging.customer.com.au can be a stable SSH alias for changing infrastructure. Keep the alias and its real target in SSH configuration or inventory, while YAML records only the alias. DNS and cloud changes then stay outside the Capistrano definition.

Building the stage generator

The generator reads YAML safely, validates each entry and writes one Ruby file per stage. This standard-library version includes a non-writing check mode:

#!/usr/bin/env ruby
require "fileutils"
require "optparse"
require "tempfile"
require "yaml"

options = { output: "config/deploy", check: false }
OptionParser.new do |parser|
  parser.on("--output DIR") { |dir| options[:output] = dir }
  parser.on("--check") { options[:check] = true }
end.parse!

source = File.expand_path(ARGV.shift || "config/capistrano/stages.yml")
output = File.expand_path(options[:output])
document = YAML.safe_load_file(source, aliases: false)
stages = document.is_a?(Hash) ? document["stages"] : nil
raise "Missing stages mapping" unless stages.is_a?(Hash) && !stages.empty?

name_pattern = /\A[a-z][a-z0-9_-]*\z/
user_pattern = /\A[a-z_][a-z0-9_]*\z/
host_pattern = /\A[A-Za-z0-9_][A-Za-z0-9_.-]*\z/
role_pattern = /\A[a-z][a-z0-9_]*\z/

stages.each_key do |stage|
  raise "Invalid stage" unless stage.is_a?(String) && stage.match?(name_pattern)
end

rendered = stages.transform_values do |config|
  servers = config.is_a?(Hash) ? config["servers"] : nil
  raise "Missing servers" unless servers.is_a?(Array) && !servers.empty?

  servers.map do |server|
    raise "Invalid server" unless server.is_a?(Hash)
    host, user, roles = server["host"], server["user"], server["roles"]
    valid = host.is_a?(String) && host.match?(host_pattern) &&
            user.is_a?(String) && user.match?(user_pattern) &&
            roles.is_a?(Array) && !roles.empty? &&
            roles.all? { |role| role.is_a?(String) && role.match?(role_pattern) }
    raise "Invalid server fields" unless valid

    port = Integer(server.fetch("port", 22))
    raise "Invalid port" unless (1..65_535).cover?(port)

    flags = []
    flags << "port: #{port}" unless port == 22
    flags << "primary: true" if server["primary"] == true
    suffix = flags.empty? ? "" : ", #{flags.join(', ')}"

    endpoint = "#{user}@#{host}"
    role_arguments = roles.map { |role| ":#{role}" }.join(", ")
    "server #{endpoint.inspect}, #{role_arguments}#{suffix}"
  end.join("\n")
end

marker = "# Generated by update_capistrano_stages.rb; do not edit.\n"
changed = false
FileUtils.mkdir_p(output) unless options[:check]

rendered.each do |stage, body|
  path = File.join(output, "#{stage}.rb")
  content = "#{marker}#{body}\n"

  if File.exist?(path) && File.read(path) == content
    puts "unchanged #{path}"
    next
  end

  changed = true
  if options[:check]
    warn "would update #{path}"
    next
  end

  Tempfile.create([".#{stage}-", ".rb"], output) do |file|
    file.write(content)
    file.flush
    File.rename(file.path, path)
  end
  puts "updated #{path}"
end

Dir.glob(File.join(output, "*.rb")).each do |path|
  first_line = File.readlines(path).first.to_s
  next unless first_line.include?("Generated by update_capistrano_stages.rb")

  stage = File.basename(path, ".rb")
  next if rendered.key?(stage)

  changed = true
  if options[:check]
    warn "would remove #{path}"
  else
    File.delete(path)
    puts "removed #{path}"
  end
end

exit(options[:check] && changed ? 1 : 0)

Each server call receives the SSH endpoint, roles and optional settings. The marker allows later runs to remove obsolete generated stages without deleting unrelated handwritten files. Keep manual overrides in a separate file loaded from deploy.rb; edits to generated output would otherwise be overwritten.

Capistrano 3 loads the selected config/deploy/<stage>.rb file. Run the generator before bundle exec cap staging deploy, then use the same process for production. The result is ordinary Capistrano DSL, so existing tasks need no adapter.

Validating changes before deployment

Validation matters more than clever rendering. safe_load_file blocks arbitrary objects and aliases; patterns reject stage names, users, roles or hosts that could change generated syntax, and the port range rejects invalid SSH values. Everything is validated before the first write, so one bad stage cannot leave a half-generated collection. On older Psych releases, use YAML.safe_load(File.read(source), aliases: false).

Treat paths as inputs. The stage-name pattern blocks / and ..; keep any output option under trusted control rather than YAML data. The Coding Journal’s explanation of PHP directory traversal attacks is a useful parallel: configuration must not escape its intended directory.

Each replacement uses a temporary file and same-filesystem rename, reducing the chance of a half-written stage. Several renames still cannot form one transaction, so Git is the recovery layer. Generate on a clean branch, inspect git diff -- config/deploy, and commit YAML and rendered files together.

Comparing stage management approaches

The practical trade-offs are:

Approach Source of truth Drift protection Practical trade-off
Handwritten stage files Ruby files Manual review Familiar, but stale hosts survive
Generated stage files YAML and generated Ruby Generator and CI Deterministic; manual edits are overwritten
Runtime variables Deployment environment Platform controls Flexible secrets, weaker host inventory

Handwritten files remain familiar, but a production server can survive long after decommissioning. Environment variables suit secrets, yet provide a weaker inventory of reachable hosts. YAML-rendered files combine one topology schema with a Git-visible copy of the exact DSL that will run. Security reviewers also get a consistent place to notice an unexpected role, host or region.

For most repositories I would choose YAML plus generated files. Keep shared tasks in deploy.rb, credentials outside both formats, and the generator’s --check result in required CI. This offers a short review surface without making every developer learn the generator.

Adding checks to the deployment workflow

Put the check where drift is cheapest to detect. A CI job can fail when the checked-in Ruby differs from the YAML:

bundle exec ruby script/update_capistrano_stages.rb --check
bundle exec cap staging deploy:check

Run the same commands locally before a pull request. The first reports drift; the second lets Capistrano verify connections and release prerequisites once stage files are current. In check mode, a non-zero exit means output needs refreshing or stale generated stages need removal.

A cross-language reference on request-aware logging middleware shows why stable identifiers and context matter; for this generator, a SHA-256 digest of each rendered file gives reviewers a compact change marker. Log source path, stage and action, but never secrets or private-key contents.

Many Australian offices treat the pause after a BYO lunch and a flat white as a release-check point: someone opens the diff and confirms the host list. That habit matters because a removed host can otherwise survive for months. The YAML diff also makes changes legible to release managers who rarely read Ruby.

Testing across Australian environments

Test the geography the application serves. A fleet serving Sydney, Melbourne and Brisbane may use AWS regions ap-southeast-2 in Sydney and ap-southeast-4 in Melbourne, while a Perth build agent connects over a long-distance link. Verify SSH latency and role selection from the deployment runner, not a laptop.

Clock differences are easy to overlook. Sydney and Melbourne observe daylight saving while Brisbane remains on AEST, so UTC logs can expose a one-hour transition. Store timestamps in UTC, include stage and region, and avoid scheduling production around a local clock without an explicit offset.

The Australian market mixes .com.au domains with direct .au registrations, and organisations may split workloads across local data centres and global providers. That variation favours stable internal aliases over embedded regional endpoints. Dry-test each alias, confirm its region in cloud tags, and let Capistrano use the same logical role everywhere.

Securing configuration and meeting local obligations

Treat YAML as topology, not a secret store. Use an SSH agent or restricted local keys, keep passphrases in an approved password manager, and inject sensitive Capistrano variables through the deployment environment. The generator emits aliases, users, roles and ports only. A compromised repository must not become a credential disclosure.

Security review has an Australian dimension. If stage records contain personal information, map handling to the Privacy Act 1988 and Australian Privacy Principles, including whether notifiable-data-breach duties apply. Australian Signals Directorate’s Essential Eight controls provide a baseline for asset inventory and controlled access. Stage metadata should still be minimised because operational details can expose systems.

Roll this out with one staging stage: commit the YAML and generated file, verify the dry run and SSH connection, then promote the same process to production. Bookmark The Coding Journal for related deployment notes, and make the next release begin from reviewed YAML rather than a hand-edited server list.


cat ~/interests.json

KeyValue
editorTerminal-first workflow
osMac OS X / Unix
vcsGit, distributed version control
deployCapistrano, cron automation
graphicsSVG, Adobe Illustrator troubleshooting
networkingIP validation, SSH, VPN

git log --oneline --reverse

2013-10-30

Solving SVG import issues in Adobe Illustrator CS6 and CC

When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.

2013

Solving NDK build issues on OS X

Troubleshooting native development kit compilation problems on Mac OS X.

2013

Programmatically adding PHP generated TypoScript to the backend configuration

Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.

2013

ArgumentError: Could not parse PKey: no start line

Debugging an SSH key parsing error encountered during deployment.

2011-08-04

Validating IP-Addresses in PHP

Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.

2011-07-09

Cocoa: Using NSTrackingArea

A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.


cat ~/contact.txt

github: github.com/x3ro
stackoverflow: x3ro
coderwall: coderwall.com/x3ro
twitter: @x3rames