Skip to content

Instantly share code, notes, and snippets.

@estum
Created September 5, 2013 04:38
Show Gist options
  • Save estum/6446177 to your computer and use it in GitHub Desktop.
Save estum/6446177 to your computer and use it in GitHub Desktop.
Capistrano task which generates nginx passenger config
# -- config/passenger.rb
# require this file in the config/deploy.rb
Capistrano::Configuration.instance.load do
# Config template path (config/passenger/template.nginx.conf)
set :template_path, File.expand_path('../passenger/template.nginx.conf', __FILE__)
# Upload config to:
set :config_deploy_path, "#{deploy_to}/config/nginx_passenger.conf"
# Nginx`s sites_enabled path
# It should be included in nginx.conf (`include /opt/nginx/sites_enabled/*;`)
set :config_enabled_path, "/opt/nginx/sites_enabled"
# Nginx`s listen_address
set :listen_address, "0.0.0.0:80"
namespace :passenger do
desc "Generates nginx config"
task :generate_nginx_config, roles: :app, except: {no_release: true} do
template = File.read(template_path)
# We can use capistrano variables in our template.
# Get required var names:
var_names = template.scan(/%{([^{}]*)}/).flatten.uniq
# Then build the hash of names and values:
config_vars = var_names.map do |var_name|
name = var_name.to_sym
[name, fetch(name)]
end
config_vars = Hash[config_vars]
# Prepare directories
run "[[ -d #{deploy_to}/log ]] || mkdir -p #{deploy_to}/log"
run "[[ -d #{deploy_to}/config ]] || mkdir -p #{deploy_to}/config"
# Upload generated config
top.put sprintf(template, config_vars), config_deploy_path, via: :scp
# Create symlink in the nginx`s sites_enabled path
run "ln -fs #{config_deploy_path} #{config_enabled_path}/01-#{domain}.conf"
end
desc "Restart nginx"
task :restart_nginx, roles: :app do
sudo "sh -c \"/etc/init.d/nginx configtest && /etc/init.d/nginx restart\"", pty: true
end
end
before "passenger:restart_nginx", "passenger:generate_nginx_config"
end
# -- config/passenger/template.nginx.conf
# use any capistrano variables inside %{}
server {
listen %{listen_address};
server_name www.%{domain};
return 301 $scheme://%{domain}$request_uri;
}
server {
listen %{listen_address};
server_name %{domain};
error_log %{deploy_to}/log/nginx.error.log debug;
root %{deploy_to}/current/public;
passenger_enabled on;
rails_env %{rails_env};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment