简体   繁体   中英

Referencing the current server in Capistrano task

How would I reference the current server in a Capistrano task? I want to curl a local file to clear the APC cache but the server does not listen on localhost so I need the server's IP address.

For instance,

role :web, "1.1.1.1", "2.2.2.2", "3.3.3.3"

task :clear_apc, :role => :web do
    run "curl http://#{WHAT_DO_I_PUT_HERE}/deploy/clearAPC.php"
end

What variable would I use so that when the task is run on 1.1.1.1 it curl s http://1.1.1.1/deploy/clearAPC.php but when run on 2.2.2.2 it calls curl s http://2.2.2.2/deploy/clearAPC.php

In Capistrano, tasks don't get executed once for each server, run executes your command on each server. Here is what you should do instead:

task :clear_apc, :role => :web do
    find_servers_for_task(current_task).each do |current_server|

        run "curl http://#{current_server.host}/deploy/clearAPC.php", :hosts => current_server.host

    end
end

The accepted answer will work, but this one lets you access the servers as variables/methods

There's the magical $CAPISTRANO:HOST$

run "curl http://$CAPISTRANO:HOST$/deploy/clearAPC.php" 

should do exactly what you want.

note: don't use it as a variable via string interpolation, capistrano will just replace the $CAPISTRANO:HOST$ in the string itself.

That's a very weird and (afaik) undocumented feature :-)

current_host = capture("echo $CAPISTRANO:HOST$").strip

Capistrano 3 - server is available as an object, with set of properties, in the roles block :

on roles(:app) do |server|

So for example to pass the hostname property to docker compose

  on roles(:app)  do |server|
    execute "docker-compose --build-arg SOME_HOST_NEEDED=#{server.hostname} ......
  end

I wanted to know the current server I was deploying to, so that I could send a message to campfire. This is what I was able to figure out, though I'm sure there is a better way

 actions = current_task.namespace.parent.logger.instance_variable_get('@options')[:actions]
 message = "I am deploying #{fetch(:latest_release).split('/').last} using cap #{actions.join(' ')}"

so when I deploy it posts this to campfire I am deploying 20121206154442 using cap QA2 campfire:notify deploy deploy:flex_master

capistrano (2.13.5) required

puts current_task.namespace.logger.instance_variable_get('@base_logger').instance_variable_get('@options')[:actions].join(' ')

figured this out by

puts current_task.namespace.logger.inspect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM