Capistrano doesn't seem to handle roles appropriately - at least how i understood them. I can't get the following simple Capfile to work as intended:
role :test1, "earzur@beta-app-01"
role :test2, "earzur@beta-app-02"
task :full_test, :roles => [:test1,:test2] do
log_test1
log_test2
end
task :log_test1, :roles => :test1 do
logger.info "TEST1 !!!"
run "echo `hostname`"
end
task :log_开发者_JAVA技巧test2, :roles => :test2 do
logger.info "TEST2 !!!"
run "echo `hostname`"
end
When i try to execute with a role restriction using ROLES=:test1, the log_test2 is still executed on the same host which is not declared as being part of role :test2 ! Is it Capistrano's expected behavior ? If it's expected, is there any way to prevent that from happening ?
ROLES=test1 cap full_test
* executing `full_test'
* executing `log_test1'
** TEST1 !!!
* executing "echo `hostname`"
servers: ["beta-app-01"]
[earzur@beta-app-01] executing command
** [out :: earzur@beta-app-01] ec2-*****.compute-1.amazonaws.com
command finished in 350ms
* executing `log_test2' <<<< shouldn't that be filtered ? because of :roles => :test2 ?
** TEST2 !!!
* executing "echo `hostname`"
servers: ["beta-app-01"]
[earzur@beta-app-01] executing command
** [out :: earzur@beta-app-01] ec2-*****.compute-1.amazonaws.com
command finished in 410ms
Thanks in advance, the related entries (http://stackoverflow.com/questions/754015/creating-a-capistrano-task-that-performs-different-tasks-based-on-role) i could find don't seem to cover that issue ...
I never understood why Capistrano acts like that, but Jamis Buck, the original maintainer of Capistrano, says that it has to be the ways it is.
To fix that, just create a xtask method and replace all your task calls with this one:
# Tasks are executed even on servers which do not have the right role
# see http://www.mail-archive.com/capistrano@googlegroups.com/msg01312.html
def xtask(name, options={}, &block)
task(name, options) do
if find_servers_for_task(current_task).empty?
logger.info '... NOT on this role!'
else
block.call
end
end
end
Also, don't define this method in a random place, like at the beginning at your Capfile. It has to be defined in a file present in the load path (who knows why). For example, write the xtask method in a new helpers/roles.rb file, and add this to your Capfile:
# Add the current directory to the load path, it's mandatory
# to load the helpers (especially the +xtask+ method)
$:.unshift File.expand_path(File.dirname(__FILE__))
require 'helpers/roles'
If you don't do that, a cap -T will show that all the tasks defined with xtask won't have any namespace, so they will overwrite each other if they have the same name in different namespaces.
精彩评论