【问题标题】:Capistrano 3 change ssh_options inside taskCapistrano 3 在任务中更改 ssh_options
【发布时间】:2014-03-30 00:43:15
【问题描述】:

我尝试使用不同的 ssh_options 在同一阶段运行 capistrano v.3 任务。

我的 production.rb 说:

set :stage, :production

set :user, 'deploy'
set :ssh_options, { user: 'deploy' }

使用此配置 capistrano 与用户 deploy 连接,这对于其余任务是正确的。但是我需要使用 an_other_user 将它连接到服务器中配置良好的特定任务。 然后我的食谱说:

...
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
...

执行时:

上限生产命名空间:my_task_with_an_other_user

capistrano 使用原始 :user "deploy"(在 production.rb 中声明的用户)进行 ssh conexion。

如何在任务中更改用户和/或 ssh_options?

【问题讨论】:

  • 嗨。我早些时候发表了评论,但这会引起一些新问题。我终于修复了它并找到了一个优雅的解决方案,刚刚更新了答案。

标签: ruby deployment capistrano capistrano3


【解决方案1】:

Capistrano 3

我很难找到解决方案。但是解决方案比第 2 版要好得多。Cap 团队做得很好。确保您已将 Capistrano 更新到 3.2.x+ 以下是诀窍:

# 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

确保 'deploy' 和 'foo' 用户都可以 ssh 进入盒子。在您的任务中,使用 on 关键字:

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

其他问题:

确保某些 Capistrano 任务会跳过您添加的额外无释放角色。否则,可能会在部署过程中导致文件权限问题。例如。 capistrano/bundler 扩展需要覆盖默认的bundler_roles

set :bundler_roles, %w(web app db)  # excludes the no release role.

Capistrano 2

我曾经有一个自定义函数来关闭和重新连接 ssh 会话。

将以下方法放入deploy.rb。拨打with_user切换ssh会话。稍微简化的版本:

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

用法:

task :update_nginx_config, :roles => :app do
  with_user "root" do
    sudo "nginx -s reload"
  end
end

【讨论】:

【解决方案2】:

@activars 的答案对我不起作用。因为当我为一个环境定义多个角色时 - 只部署了一个:(

所以我的解决方案是创建几个环境,例如production.rbproductionroot.rb

productionroot 的内容带有 no_release=true 标志 - 正如您指定的那样:

server '146.120.89.81', user: 'root', roles: %w{foo_role}, no_release: true

之后我创建了运行的 sh 脚本

#/usr/bin/env bash
bundle exec cap production deploy
bundle exec cap productionroot deploy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 2013-11-17
    • 2016-11-08
    • 1970-01-01
    • 2015-08-19
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多