Capistrano 3 change ssh_options inside task

后端 未结 2 912
既然无缘
既然无缘 2020-12-18 06:38

I trying to run capistrano v.3 task in same stage with diferent ssh_options.

my production.rb say:

set :stag         


        
2条回答
  •  抹茶落季
    2020-12-18 07:29

    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
    

提交回复
热议问题