Trying to set custom SCM on Capistrano 3.8.1 - ruby

I am configuring a custom SCM because i don't need the default git in the development local environment, but i would like to trigger a custom logic, mainly based on creating a release starting from a source_directory.
As described in the documentation (http://capistranorb.com/documentation/advanced-features/custom-scm/) i wrote a module that extends the Capistrano::Plugin, and set required methods to handle the custom SCM implementation used by deploy Capistrano flow.
Besides this, when i put in my config/deploy/<environment>.rb the entry:
set :scm, :<custom plugin name>
Capistrano keeps to use the default git scm, even if is not declared.
in my Capfile there are loaded both as follow:
require_relative 'scm/local.rb'
install_plugin Capistrano::LocalPlugin
require 'capistrano/git
install_plugin Capistrano::SCM::Git
Here also the module of custom SCM :
require 'capistrano/scm/plugin'
module Capistrano
class Capistrano::SCM::LocalPlugin < ::Capistrano::Plugin
def set_defaults
set_if_empty :source_dir, 'non-exisisting-dir'
end
def define_tasks
namespace :local do
task :create_release do
run_locally do
execute :mkdir, '-p', :'tmp'
execute "cd #{fetch(:source_dir)} && tar -cz --exclude tests --exclude vendor --exclude .git --exclude node_modules --exclude tmp/#{fetch(:release_timestamp)}.tar.gz -f tmp/#{fetch(:release_timestamp)}.tar.gz ."
end
on release_roles :all do
execute :mkdir, '-p', release_path
upload! "tmp/#{fetch(:release_timestamp)}.tar.gz", "#{release_path}/#{fetch(:release_timestamp)}.tar.gz"
execute "tar -xvf #{release_path}/#{fetch(:release_timestamp)}.tar.gz --directory #{release_path}"
execute "rm #{release_path}/#{fetch(:release_timestamp)}.tar.gz"
end
run_locally do
execute "rm -rf tmp"
end
end
desc 'Determine the revision that will be deployed'
task :set_current_revision do
run_locally do
set :current_revision, capture(:git, " --git-dir #{fetch(:source_dir)}/.git rev-parse --short #{fetch(:branch)}")
end
end
end
end
def register_hooks
after 'deploy:new_release_path', 'local:create_release'
end
end
end
Does anyone know which is the black magic to use in order to say to Capistrano to use my scm instead of the default git one ?

set :scm, 'myscm' is deprecated. Until the next major version of Capistrano (4.0), there is a class which checks for an SCM having been installed via install_plugin, and if not, checks for the set :scm definition. If install_plugin has been called, then set :scm is ignored and deleted.
install_plugin only registers the plugin. It looks to me from the code that Capistrano will run both plugins if two are installed.
So, in a nutshell, Capistrano doesn't support selecting multiple SCMs based on environment. The closest thing to that you could try is using an environment variable to conditionally load the SCM in your Capfile. Something like:
if ENV['CAP_SCM'] == 'local'
require_relative 'scm/local.rb'
install_plugin Capistrano::LocalPlugin
else
require 'capistrano/git'
install_plugin Capistrano::SCM::Git
end
This is all documented here: https://github.com/capistrano/capistrano/blob/master/UPGRADING-3.7.md

Related

Mina Deploy uses wrong user

I got some issue with the gem 'mina'. If I do set :user, 'username', he tries to connect to the server via Username#xxx.... wich is not working if the user is not existing. My PC is name Username. So mina setup and mina deploy are not working.
Does someone know a solution?.
Thanks
Best regards
Matze
EDIT:
Gemfile:
gem 'mina'
After that I run bundle install and mina init
deploy.rb:
require 'mina/rails'
require 'mina/git'
# require 'mina/rbenv' # for rbenv support. (https://rbenv.org)
require 'mina/rvm' # for rvm support. (https://rvm.io)
# Basic settings:
# domain - The hostname to SSH to.
# deploy_to - Path to deploy into.
# repository - Git repo to clone from. (needed by mina/git)
# branch - Branch name to deploy. (needed by mina/git)
set :user, "user"
set :application_name, 'appname'
set :domain, 'xx.xxx.xxx.xxx'
set :deploy_to, '/var/www/user/appname'
set :repository, 'user#xx.xxx.xxx.xxx:/home/user/git/appname.git'
set :branch, 'master'
# Optional settings:
# set :user, 'user' # Username in the server to SSH to.
# set :port, '30000' # SSH port number.
# set :forward_agent, true # SSH forward_agent.
# Shared dirs and files will be symlinked into the app-folder by the 'deploy:link_shared_paths' step.
# Some plugins already add folders to shared_dirs like `mina/rails` add `public/assets`, `vendor/bundle` and many more
# run `mina -d` to see all folders and files already included in `shared_dirs` and `shared_files`
# set :shared_dirs, fetch(:shared_dirs, []).push('public/assets')
set :shared_files, fetch(:shared_files, []).push('config/database.yml', 'config/secrets.yml')
# This task is the environment that is loaded for all remote run commands, such as
# `mina deploy` or `mina rake`.
task :remote_environment do
# If you're using rbenv, use this to load the rbenv environment.
# Be sure to commit your .ruby-version or .rbenv-version to your repository.
# invoke :'rbenv:load'
# For those using RVM, use this to load an RVM version#gemset.
# invoke :'rvm:use', 'ruby-1.9.3-p125#default'
end
# Put any custom commands you need to run at setup
# All paths in `shared_dirs` and `shared_paths` will be created on their own.
task :setup do
# command %{rbenv install 2.3.0 --skip-existing}
end
desc "Deploys the current version to the server."
task :deploy do
# uncomment this line to make sure you pushed your local branch to the remote origin
# invoke :'git:ensure_pushed'
deploy do
# Put things that will set up an empty directory into a fully set-up
# instance of your project.
invoke :'git:clone'
invoke :'deploy:link_shared_paths'
invoke :'bundle:install'
invoke :'rails:db_migrate'
invoke :'rails:assets_precompile'
invoke :'deploy:cleanup'
on :launch do
in_path(fetch(:current_path)) do
command %{mkdir -p tmp/}
command %{touch tmp/restart.txt}
end
end
end
# you can use `run :local` to run tasks on local machine before of after the deploy scripts
# run(:local){ say 'done' }
end
# For help in making your deploy script, see the Mina documentation:
#
# - https://github.com/mina-deploy/mina/tree/master/docs
set :execution_mode, :exec if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
When I run now mina setup he print that:
$ mina setup
User#xx.xxx.xxx.xxx's password:
SSH Auth key working fine and git working fine he just puts User instead of user before the ip, what is not working because the user just exists with small letter. But my working machine is named User.

Symfony: generate assetics

I use Capistrano and Symfony plugin ( https://github.com/capistrano/symfony ) for my deployment (I have Symfony 2.7). But, my CSS is wrong. I think assetic is not generated.
I used default deploy.rb and added ACL commands for chmod.
# config valid only for current version of Capistrano
lock '3.5.0'
set :application, 'Dometech.fr'
set :repo_url, 'ssh://git#37.187.154.125:9325/var/www/depotsGit/dometech.git/'
# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, '/var/www/dev/Dometech'
set :symfony_directory_structure, 2
namespace :deploy do
after "deploy:updated" , "composer:install"
# Clear ACL only before switching version
before "deploy:publishing" , "symfony:fixes_acl"
end
namespace :symfony do
desc "Add ACL on cache directory"
task :fixes_acl do
on roles :web do
execute :setfacl, "-R -m u:www-data:rwX #{fetch(:release_path)}/app/cache #{fetch(:release_path)}/app/logs"
end
end
end
Can you help me for assetic?
Apparently, the Symfony Capistrano plugin removed Assetic support, so you should add a task to your deploy.rb to take care of it. You can probably just take what was removed:
set :assetic_dump_flags, ''
namespace :assetic do
desc "Dump assets with Assetic"
task :dump do
on release_roles(:all) do
symfony_console "assetic:dump", fetch(:assetic_dump_flags)
end
end
end
and make sure it’s invoked with something like:
after 'deploy:updated', 'symfony:assetic:dump'

Capistrano Deploy, access ActiveRecord

Okay,
I'm sorry if the title is not descriptive enough, but allow me to explain what I want to achieve:
I have a Rails 3 application
During my deploy, it needs to call pg_dump with the correct parameters to restore a backup
The task needs to be ran after the deploy is done but before the migrations.
The problem I have however, is that for this task, I would like to access Rails specific code, which is not working as Capistrano keeps throwing a lot of errors at me like gems not available or module not defined.
This is my Rake task:
namespace :deploy do
namespace :rm do
desc 'Backup the database'
task :backup do
# Generates the command to invoke the Rails runner
# Used by the cfg method to execute the ActiveRecord configuration in the rails config.
def runner
dir = "#{fetch(:deploy_to)}/current"
bundler = "#{SSHKit.config.command_map.prefix[:bundle].first} bundle exec"
env = fetch(:rails_env)
"cd #{dir}; #{bundler} rails r -e #{env}"
end
def cfg(name)
env = fetch(:rails_env)
command = "\"puts ActiveRecord::Base.configurations['#{env}']['#{name}']\""
"#{runner} #{command}"
end
on roles(:db) do
timestamp = Time.now.strftime('%Y%m%d%H%M%S')
backups = File.expand_path(File.join(fetch(:deploy_to), '..', 'backups'))
execute :mkdir, '-p', backups
dump = "PGPASSWORD=`#{cfg('password')}` pg_dump -h `#{cfg'host')}` -U `#{cfg('username')}` `#{cfg('database')}`"
fn = "#{timestamp}_#{fetch(:stage)}.sql.gz"
path = File.join(backups, fn)
execute "#{dump} | gzip > #{path}"
end
end
end
end
In it's current form, it simply generates a string with the runner method and dumps that inside the cfg method.
I tried rewriting the runner method, but for some reason I keep getting the runner --help output from the remote server, but the command being generated in the output is correct, and works locally just fine.
We are using Ruby 2.2.2 and RVM on the remote server.
Is it even possible to do what we are trying to construct together?
I'd suggest writing a rake task inside your Rails app and invoking that from your Capistrano task. This is how the Capistrano rails tasks work.
within release_path do
with rails_env: fetch(:rails_env) do
execute :rake, "db:migrate"
end
end

Capistrano 3 change ssh_options inside task

I trying to run capistrano v.3 task in same stage with diferent ssh_options.
my production.rb say:
set :stage, :production
set :user, 'deploy'
set :ssh_options, { user: 'deploy' }
With this configuration capistrano connect with user deploy which is correct for the rest of taks. But I need connect it for one specific task with an_other_user wich is well configured in server.
Then my recipe say:
...
tasks with original user
...
task :my_task_with_an_other_user do
set :user, 'an_other_user'
set :ssh_options, { user: 'an_other_user' }
on roles(:all) do |host|
execute :mkdir, '-p', 'mydir'
end
end
...
other tasks with original user
...
When execute:
cap production namespace:my_task_with_an_other_user
capistrano make ssh conexion with original :user "deploy" (the user declared in production.rb).
How can I change the user and/or ssh_options it inside task?
Capistrano 3
I had hard time finding out a solution. But the solution is much nicer than version 2. Cap team has done a great job. Make sure you have updated Capistrano to 3.2.x+ Here's the trick:
# in config/deploy/production.rb, or config/deploy/staging.rb
# These roles are used for deployment that works with Cap hooks
role :app, %w{deploy#myserver.com}
role :web, %w{deploy#myserver.com}
role :db, %w{deploy#myserver.com}
# Use additional roles to run side job out side Capistrano hooks
# 'foo' is another ssh user for none-release purpose tasks (mostly root tasks).
# e.g. user 'deploy' does not have root permission, but 'foo' has root permission.
# 'no_release' flag is important to flag this user will skip some standard hooks
# (e.g. scm/git/svn checkout )
role :foo_role, %w{foo#myserver.com}, no_release: true
Make sure both 'deploy' & 'foo' user can ssh into the box. Within your tasks, use the on keyword:
task :restart do
on roles(:foo_role) do
sudo "service nginx restart"
end
end
task :other_standard_deployment_tasks do
on release_roles(:all) do
# ...
end
end
Other gotchas:
Make sure some Capistrano tasks skips the additional no release role you added. Otherwise, it might cause file permission issues during deployment. E.g. capistrano/bundler extension need to override the default bundler_roles
set :bundler_roles, %w(web app db) # excludes the no release role.
Read more about no_release flag: related Github issue.
Capistrano 2
I used to have a custom functions to close and reconnect ssh sessions.
Reference Paul Gross's Blog
Place the following methods in deploy.rb. Call with_user to switch ssh session. Slightly simplified version:
def with_user(new_user, &block)
old_user = user
set :user, new_user
close_sessions
yield
set :user, old_user
close_sessions
end
def close_sessions
sessions.values.each { |session| session.close }
sessions.clear
end
Usage:
task :update_nginx_config, :roles => :app do
with_user "root" do
sudo "nginx -s reload"
end
end
Answer of #activars didn't work for me. Because when I defined several roles for one environment - only one was deployed :(
So my solution was to create several enviroments, e.g. production.rb and productionroot.rb.
productionroot has content with no_release=true flag - just as you've specified:
server '146.120.89.81', user: 'root', roles: %w{foo_role}, no_release: true
After that I've created sh script which runs
#/usr/bin/env bash
bundle exec cap production deploy
bundle exec cap productionroot deploy

Mina deployment : invoke task once `current` symlink is updated

I'm using Mina (a simpler alternative to Capistrano) to deploy my ruby websites, and I am trying to run some tasks once the current symlink has been updated.
So far, here's what I have in my deploy.rb file:
desc "Deploys the current version to the server."
task :deploy => :environment do
deploy do
invoke :'git:clone'
invoke :'deploy:link_shared_paths'
invoke :'bundle:install'
to :launch do
invoke :restart
end
end
end
desc "Manually restart Thin web server"
task :restart do
in_directory "#{deploy_to}/current" do
queue! %[bundle exec thin restart -C "#{thin_yml}"]
end
end
My problem is that when Mina hits the to :launch block, the current symlink has not yet been updated, so either it does not exist (if it is the 1st deployment for this project) or it's still pointing to the n-1 release (and thus, the server uses an outdated version of the project).
So I'd like to be able to invoke my :restart task once the new release has been moved to the release directory and the current symlink has been updated.
I think it's a bug of Mina. in_directory seems to not work properly when used inside a to context. A quick and dirty workaround would be adding #commands[:default] = commands(#to) at the end of the in_directory block.
desc "Manually restart Thin web server"
task :restart do
in_directory "#{deploy_to}/current" do
queue! %[bundle exec thin restart -C "#{thin_yml}"]
#commands[:default] = commands(#to)
end
end

Resources