Programming

Capistrano에서 레이크 작업을 실행하려면 어떻게해야합니까?

procodes 2020. 8. 18. 19:21
반응형

Capistrano에서 레이크 작업을 실행하려면 어떻게해야합니까?


프로덕션 서버에 앱을 배포 할 수있는 deploy.rb가 이미 있습니다.

내 앱에는 사용자 지정 레이크 작업 (lib / tasks 디렉터리의 .rake 파일)이 포함되어 있습니다.

레이크 작업을 원격으로 실행할 캡 작업을 만들고 싶습니다.


좀 더 명시 적으로에서 \config\deploy.rb작업 또는 네임 스페이스 외부에 추가합니다.

namespace :rake do  
  desc "Run a task on a remote server."  
  # run like: cap staging rake:invoke task=a_certain_task  
  task :invoke do  
    run("cd #{deploy_to}/current; /usr/bin/env rake #{ENV['task']} RAILS_ENV=#{rails_env}")  
  end  
end

그런 다음에서 다음 /rails_root/을 실행할 수 있습니다.

cap staging rake:invoke task=rebuild_table_abc

run("cd #{deploy_to}/current && /usr/bin/env rake `<task_name>` RAILS_ENV=production")

Google에서 찾았습니다 -http : //ananelson.com/said/on/2007/12/30/remote-rake-tasks-with-capistrano/

RAILS_ENV=production내가 처음에 그것을 생각하지 않았고 작업이 아무것도되지 않은 이유를 알아낼 수 - 잡았다이었다.


... 몇 년 후 ...

capistrano의 rails 플러그인 을 살펴보면 https://github.com/capistrano/rails/blob/master/lib/capistrano/tasks/migrations.rake#L5-L14에서 볼 수 있습니다.

desc 'Runs rake db:migrate if migrations are set'
task :migrate => [:set_rails_env] do
  on primary fetch(:migration_role) do
    within release_path do
      with rails_env: fetch(:rails_env) do
        execute :rake, "db:migrate"
      end
    end
  end
end

Capistrano 3 Generic 버전 (모든 레이크 작업 실행)

Mirek Rusin의 대답의 일반 버전을 작성하십시오.

desc 'Invoke a rake command on the remote server'
task :invoke, [:command] => 'deploy:set_rails_env' do |task, args|
  on primary(:app) do
    within current_path do
      with :rails_env => fetch(:rails_env) do
        rake args[:command]
      end
    end
  end
end

사용 예 : cap staging "invoke[db:migrate]"

참고 deploy:set_rails_env필요는 카피 스트라 노 레일 보석에서 온다


Capistrano 스타일 레이크 호출 사용

require 'bundler/capistrano'레이크를 수정하는 다른 확장 프로그램과 "그냥 작동"하는 일반적인 방법이 있습니다. 다단계를 사용하는 경우 사전 프로덕션 환경에서도 작동합니다. 요점? 가능한 경우 구성 변수를 사용하십시오.

desc "Run the super-awesome rake task"
task :super_awesome do
  rake = fetch(:rake, 'rake')
  rails_env = fetch(:rails_env, 'production')

  run "cd '#{current_path}' && #{rake} super_awesome RAILS_ENV=#{rails_env}"
end

capistrano-rake보석 사용

커스텀 카피 스트라 노 레시피를 엉망으로 만들지 않고 gem을 설치하고 다음과 같이 원격 서버에서 원하는 레이크 작업을 실행하십시오.

cap production invoke:rake TASK=my:rake_task

전체 공개 : 내가 썼다


개인적으로 프로덕션에서 다음과 같은 도우미 메서드를 사용합니다.

def run_rake(task, options={}, &block)
  command = "cd #{latest_release} && /usr/bin/env bundle exec rake #{task}"
  run(command, options, &block)
end

이를 통해 run (command) 메서드를 사용하는 것과 유사한 rake 작업을 실행할 수 있습니다.


참고 : Duke가 제안한 것과 비슷 하지만 저는 :

  • current_release 대신 latest_release를 사용하십시오. 내 경험상 rake 명령을 실행할 때 기대하는 것이 더 많습니다.
  • Rake 및 Capistrano의 명명 규칙을 따릅니다 (대신 : cmd-> task 및 rake-> run_rake).
  • RAILS_ENV = # {rails_env}를 설정하지 마십시오. 올바른 위치는 default_run_options 변수이기 때문입니다. 예 : default_run_options [: env] = { 'RAILS_ENV'=> 'production'} #-> DRY!

갈퀴 작업을 Capistrano 작업으로 사용할 수있게 해주는 흥미로운 보석 망토 가 있으므로 원격으로 실행할 수 있습니다. cape잘 문서화되어 있지만 여기에 i를 설정하는 방법에 대한 간략한 개요가 있습니다.

gem을 설치 한 후 이것을 config/deploy.rb파일에 추가 하십시오.

# config/deploy.rb
require 'cape'
Cape do
  # Create Capistrano recipes for all Rake tasks.
  mirror_rake_tasks
end

이제 rake.NET을 통해 모든 작업을 로컬 또는 원격으로 실행할 수 있습니다 cap.

추가 보너스 cape로 레이크 작업을 로컬 및 원격으로 실행하는 방법을 설정할 수 있습니다 (더 이상은 bundle exec rake아님). 다음을 config/deploy.rb파일에 추가하기 만하면 됩니다.

# Configure Cape to execute Rake via Bundler, both locally and remotely.
Cape.local_rake_executable  = '/usr/bin/env bundle exec rake'
Cape.remote_rake_executable = '/usr/bin/env bundle exec rake'

namespace :rake_task do
  task :invoke do
    if ENV['COMMAND'].to_s.strip == ''
      puts "USAGE: cap rake_task:invoke COMMAND='db:migrate'" 
    else
      run "cd #{current_path} && RAILS_ENV=production rake #{ENV['COMMAND']}"
    end
  end                           
end 

레이크 작업 실행을 단순화하기 위해 deploy.rb에 넣은 내용은 다음과 같습니다. 카피 스트라 노의 run () 메서드를 둘러싼 간단한 래퍼입니다.

def rake(cmd, options={}, &block)
  command = "cd #{current_release} && /usr/bin/env bundle exec rake #{cmd} RAILS_ENV=#{rails_env}"
  run(command, options, &block)
end

그런 다음 다음과 같이 레이크 작업을 실행합니다.

rake 'app:compile:jammit'

이것은 나를 위해 일했습니다.

task :invoke, :command do |task, args|
  on roles(:app) do
    within current_path do
      with rails_env: fetch(:rails_env) do
        execute :rake, args[:command]
      end
    end
  end
end

그런 다음 간단히 실행 cap production "invoke[task_name]"


Most of it is from above answer with a minor enhancement to run any rake task from capistrano

Run any rake task from capistrano

$ cap rake -s rake_task=$rake_task

# Capfile     
task :rake do
  rake = fetch(:rake, 'rake')
  rails_env = fetch(:rails_env, 'production')

  run "cd '#{current_path}' && #{rake} #{rake_task} RAILS_ENV=#{rails_env}"
end

This also works:

run("cd #{release_path}/current && /usr/bin/rake <rake_task_name>", :env => {'RAILS_ENV' => rails_env})

More info: Capistrano Run


If you want to be able to pass multiple arguments try this (based on marinosbern's answer):

task :invoke, [:command] => 'deploy:set_rails_env' do |task, args|
  on primary(:app) do
    within current_path do
      with :rails_env => fetch(:rails_env) do
        execute :rake, "#{args.command}[#{args.extras.join(",")}]"
      end
    end
  end
end

Then you can run a task like so: cap production invoke["task","arg1","arg2"]


So I have been working on this. it seams to work well. However you need a formater to really take advantage of the code.

If you don't want to use a formatter just set the log level to to debug mode. These semas to h

SSHKit.config.output_verbosity = Logger::DEBUG

Cap Stuff

namespace :invoke do
  desc 'Run a bash task on a remote server. cap environment invoke:bash[\'ls -la\'] '
  task :bash, :execute do |_task, args|
    on roles(:app), in: :sequence do
      SSHKit.config.format = :supersimple
      execute args[:execute]
    end
  end

  desc 'Run a rake task on a remote server. cap environment invoke:rake[\'db:migrate\'] '
  task :rake, :task do |_task, args|
    on primary :app do
      within current_path do
        with rails_env: fetch(:rails_env) do
          SSHKit.config.format = :supersimple
          rake args[:task]
        end
      end
    end
  end
end

This is the formatter I built to work with the code above. It is based off the :textsimple built into the sshkit but it is not a bad way to invoke custom tasks. Oh this many not works with the newest version of sshkit gem. I know it works with 1.7.1. I say this because the master branch has changed the SSHKit::Command methods that are available.

module SSHKit
  module Formatter
    class SuperSimple < SSHKit::Formatter::Abstract
      def write(obj)
        case obj
        when SSHKit::Command    then write_command(obj)
        when SSHKit::LogMessage then write_log_message(obj)
        end
      end
      alias :<< :write

      private

      def write_command(command)
        unless command.started? && SSHKit.config.output_verbosity == Logger::DEBUG
          original_output << "Running #{String(command)} #{command.host.user ? "as #{command.host.user}@" : "on "}#{command.host}\n"
          if SSHKit.config.output_verbosity == Logger::DEBUG
            original_output << "Command: #{command.to_command}" + "\n"
          end
        end

        unless command.stdout.empty?
          command.stdout.lines.each do |line|
            original_output << line
            original_output << "\n" unless line[-1] == "\n"
          end
        end

        unless command.stderr.empty?
          command.stderr.lines.each do |line|
            original_output << line
            original_output << "\n" unless line[-1] == "\n"
          end
        end

      end

      def write_log_message(log_message)
        original_output << log_message.to_s + "\n"
      end
    end
  end
end

Previous answers didn't help me and i found this: From http://kenglish.co/run-rake-tasks-on-the-server-with-capistrano-3-and-rbenv/

namespace :deploy do
  # ....
  # @example
  #   bundle exec cap uat deploy:invoke task=users:update_defaults
  desc 'Invoke rake task on the server'
  task :invoke do
    fail 'no task provided' unless ENV['task']

    on roles(:app) do
      within release_path do
        with rails_env: fetch(:rails_env) do
          execute :rake, ENV['task']
        end
      end
    end
  end

end

to run your task use

bundle exec cap uat deploy:invoke task=users:update_defaults

Maybe it will be useful for someone

참고URL : https://stackoverflow.com/questions/312214/how-do-i-run-a-rake-task-from-capistrano

반응형