如何在服务器而不是本地运行此Capistrano任务?

时间:2012-12-06 01:04:27

标签: ruby shell ssh capistrano

我想从目录中提取最后一个修改过的文件。这个capistrano任务在本地运行很好,但是如何让它在服务器上运行以便我可以提取服务器数据呢?

namespace :pull do
  desc "Hello Pull data from the server"
  task :hello, roles: :db do
    ## Want this to return what's on the server. Not locally.
    puts "Getting filename of last created database backup"
    db_backups_directory_path = "/home/deployer/backups"
    last_db_backup_archived = Dir.glob(File.join(db_backups_directory_path, '*')).
                              select  {|f| File.file? f }.
                              sort_by {|f| File.mtime f }.
                              last
    puts last_db_backup_archived
  end
end

2 个答案:

答案 0 :(得分:1)

我会选择run。 Capistrano在一堆服务器上并行执行命令,因此您必须将ruby转换为shell代码。值得庆幸的是,在您的情况下,它或多或少是一种简单的翻译。

task :hello, roles: :db do
  ## Want this to return what's on the server. Not locally.
  puts "Getting filename of last created database backup"
  db_backups_directory_path = "/home/deployer/backups"
  run <<-CMD
     find #{db_backups_directory_path} -type f -printf '%A@ %p\n'|
     sort -n | tail -n1 | cut -d" "  -f2
  CMD
end

答案 1 :(得分:1)

capture命令也将在远程服务器上运行。除了远程运行命令外,它还可以将命令的stdout写入ruby变量。因此,您可以使用ruby方法对其进行操作,然后使用

将其传回
some_variable = capture ("pwd")
capture ("cd #{some_variable}/.. && ls -alh")

这不是最好的例子,但你得到了一般的想法。第二个capture显然不是必需的,你可以用run替换它,它不会有所作为。

但是,如果您针对多个服务器运行此任务,您应该知道这不起作用。

来自文档:

  

在目标服务器上执行给定命令   当前任务,将它的stdout收集到一个字符串中,然后返回   串。该命令通过#invoke_command调用。

     

http://rdoc.info/github/capistrano/capistrano/Capistrano/Configuration/Actions/Inspect#capture-instance_method