Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 425 lines (277 sloc) 20.3 kB
de8843d @leehambley More stuff here\!
authored
1 Capistrano Handbook
2 ===================
3
4 ## Index
5
6 * [Simple. The Way it Should Be](simple_the_way_it_should_be)
7 * [Building Blocks Variables & Tasks](building_blocks_varaibles_and_tasks)
8 * [Tasks](building_blocks_varaibles_and_tasks/tasks)
9 * [Variables](building_blocks_varaibles_and_tasks/variables)
10 * [Local Vs. Remote Tasks](/local_vs_remote_tasks)
11 * [Rights, Users and Privileges](/rights_users_privileges)
12 * [Command Line Options](/command_line_options)
13
14 ### Anatomy of a Capistrano installation
15
16 Typically inside your application you will have a structure not dissimilar to the following:
17
18 /
19 |- public/
20 |- config/
21 |- application/
22
23 Regardless of your application's nature you would usually expect to have these directories; whether or not they exist is largely academic.
24
25 Capistrano relies on you having a `config` directory into which it will install a `deploy.rb` file that contains your settings.
26
27 The `deploy.rb` file is loaded when you call `cap` on the command line; in the event that you aren't in the root of your application (or more accurately that there isn't a `capfile`) in your present working directory, `cap` will search up the directory structure until it finds one, this may include your home directory.
28
29 **Beware of this when dealing with multiple projects, or nested projects - this feature was intended so that you could run a deploy, or open a [`cap shell`](http://weblog.jamisbuck.org/2006/9/21/introducing-the-capistrano-shell) without moving to the root of your application.**
30
31 Typically `capifying` an application will create something akin to the following:
32
33 set :application, "set your application name here"
34 set :repository, "set your repository location here"
35
36 # If you aren't deploying to /u/apps/#{application} on the target
37 # servers (which is the default), you can specify the actual location
38 # via the :deploy_to variable:
39 # set :deploy_to, "/var/www/#{application}"
40
41 # If you aren't using Subversion to manage your source code, specify
42 # your SCM below:
43 # set :scm, :subversion
44
45 role :app, "your app-server here"
46 role :web, "your web-server here"
47 role :db, "your db-server here", :primary => true
48
49 If your application is not separated into `application`, `web` and `database` servers, you can either set them to be the same value; or comment out, or remove the one you do not require.
50
51 Typically for a `PHP` application one would expect to comment out the `web` or `app` roles, depending on your requirements. Certain built in tasks expect to run only on one, or the other kind of server.
52
53 The `:primary => true` part of the role definitions allows you to have more than one database server, this could easily also be written either of the following two ways:
54
55 role :db, 'db1.example.com', 'db2.example.com'
56 -- or --
57 role :db, 'db1.example.com', 'db2.example.com', :primary => true
58
59 If you have two servers, and neither is `primary`, or
60
61 role :db, 'db1.example.com', :primary => true
62 role :db, 'db2.example.com'
63
64 If, for example when deploying a Rails application you only wanted `db1` to run migrations, in the first example both might.
65
66 Essentially when using the Rails deployment recipes, the `:primary` option defines where database migrations are run.
67
68 Similar attributes include `:no_release` often used for the `:web` role by some of the recipes in circulation to decide which servers should not have the code checked out to them.
69
70 Attributes like these are arbitrary and you can define some of your own, and use them to filter more precisely where your own tasks run,
71
72 You may want to read more about the [`role`](http://wiki.capify.org/index.php/Role) method as it has a few options. There is the alternate [`server`] method which works slightly differently, the examples should demonstrate how-so.
73
74 role :db, 'www.example.com'
75 role :app, 'www.example.com'
76 role :web, 'www.example.com'
77
78 And the `server` method:
79
80 server 'www.example.com', :app, :web, :db
81
82 If you have a lot of multi-function servers, or perhaps just one server running your whole application the `server` method may be a quick and easy way to remove a few LOC and a little confusion from your deployment configuration files.
83
84 Other than the shorter syntax, they are functionally equivalent.
85
86 ### Building Blocks Variables & Tasks
87
88 #### Tasks
89
90 Tasks are the foundation of a Capistrano setup; collections of tasks are typically called _Recipes_.
91
92 Tasks are defined as such, and can be defined anywhere inside your `Capfile` or `deploy.rb`; or indeed any other file you care to load into the `Capfile` at runtime.
93
94 desc "Search Remote Application Server Libraries"
95 task :search_libs, :roles => :app do
96 run "ls -x1 /usr/lib | grep -i xml"
97 end
98
99 Lets break that down a little...
100
101 The [`desc`](http://wiki.capify.org/index.php/Desc) method defines the task description, this shows up when using `cap -T` on your application.. these are arbitrary description strings that can be used to help your users or fellow developers.
102
103 Tasks without a `desc`ription will not be listed by a default `cap -T`, but will however be listed with a `cap -Tv`. More command line options for the `cap` script will be discussed later in the handbook.
104
105 The [`task`](http://wiki.capify.org/index.php/Task) method expects a block, that is run when the task is invoked. The task can, typically contain any number of instructions, both to run locally and on your deployment target servers (`app`,`web`,`db`).
106
107 ##### Namespacing Tasks
108
109 It stands to reason that with such a wide scope of available uses, there would be potential for naming clashes, this isn't a problem localized to Capistrano; and elsewhere in the computer sciences world this has been solved with Namespacing; Capistrano is no different, take the following example:
110
111 desc "Backup Web Server"
112 task :backup_web_server do
113 puts "In Example Backup Web-Server"
114 end
115
116 desc "Backup Database Server"
117 task :backup_database_server do
118 puts "In Example Backup Database-Server"
119 end
120
121 Defining a task in this way, and more about how the task blocks are arranged is forthcoming; however imagine we had two tasks `backup` perhaps, that needed to work differently on different roles.. here's how namepsaces solve that problem
122
1a239ea @dhl Proper formatting of code example in the Namespacing Tasks section.
dhl authored
123 namespace :web_server do
124 task :backup do
125 puts "In Example Backup Web-Server"
126 end
de8843d @leehambley More stuff here\!
authored
127 end
128
1a239ea @dhl Proper formatting of code example in the Namespacing Tasks section.
dhl authored
129 namespace :database_server do
130 task :backup do
131 puts "In Example Backup Database-Server"
132 end
de8843d @leehambley More stuff here\!
authored
133 end
134
135 Whilst the tasks in the first example might be listed by `cap -T` as:
136
137 backup_database_server Backup Database Server
138 backup_web_server Backup Web Server
139
140 And invoked with either `cap backup_database_server` or `cap backup_web_server`; the second pair of examples would be listed by `cap -T` as
141
142 database_server:backup Backup Database Server
143 web_server:backup Backup Web Server
144
145 and similarly invoked with `cap database_server:backup` or `cap web_server:backup`
146
147 Namespaces have an implicit `default` task called if you address the namespace as if it were a task, consider the following example:
148
149 namespace :backup do
150
151 task :default do
152 web
8e19f17 @maciejsmolinski Correcting task name being called (old name probably was used). Will …
maciejsmolinski authored
153 db
de8843d @leehambley More stuff here\!
authored
154 end
155
156 task :web, :roles => :web do
157 puts "Backing Up Web Server"
158 end
159
160 task :db, :roles => :db do
161 puts "Backing Up DB Server"
162 end
163
164 end
165
166 **Note:** These are nested differently to the two previous examples, as when looked at in these terms it makes a lot more sense to namespace them this way, and simply call the following
167
168 * To backup just the web server:
169
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
170 $ cap backup:web
de8843d @leehambley More stuff here\!
authored
171
172 * To backup just the db server:
173
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
174 $ cap backup:db
de8843d @leehambley More stuff here\!
authored
175
176 * To back up both in series:
177
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
178 $ cap backup
de8843d @leehambley More stuff here\!
authored
179
b64294b @natedavisolds Typo "they syntax" to "the syntax"
natedavisolds authored
180 It is important to note here that when calling tasks from within tasks, unlike with `rake` where the syntax might be something like `Rake::Tasks['backup:db'].invoke`, with Capistrano you simply name the task as if it were any other ruby method.
de8843d @leehambley More stuff here\!
authored
181
182 When calling tasks cross-namespace, or for readability you can (and often should) prefix the task call with the namespace in which the task resides, for example:
183
184 namespace :one do
185 task :default do
186 test
187 one.test
188 two.test
189 end
190 task :test do
191 puts "Test One Successful!"
192 end
193 end
194
195 namespace :two do
196 task :test do
197 puts "Test Two Successful"
198 end
199 end
200
201 Calling `cap one` would output:
202
203 Test One Successful
204 Test One Successful
205 Test Two Successful
206
207 This gets slightly more complicated as the namespace hierarchy becomes more intricate but the same principles always apply.
208
209 Namespaces are nestable, an example from one of the core methods is `cap deploy:web:disable` a `disable` task in the `web` namespace which in turn resides in the `deploy` namespace.
210
211 There is a `top` namespace for convenience, and it is here that methods defined outside of an explicit `namespace` block reside by default. If you are in a task inside a namespace, and you want to call a task from a _higher_ namespace, or outside of them all, prefix it with `top` and you can define the path to the task you require.
212
213 ##### Existing Tasks
214
215 Unlike [`rake`](http://rake.rubyforge.org/) when you define a task that collides with the name of another (within the same namespace) it will overwrite the task rather than adding to it.
216
217 ##### Chaining Tasks
218
219 As this is considered to be a feature, not a limitation of Capistrano; there is an exceptionally easy way to chain tasks, including but not limited to the `default` task for each namespace, consider the following
220
221 namespace :deploy do
222 # .. this is a default namespace with lots of its own tasks
223 end
224
225 namespace :notifier do
226 task :email_the_boss do
227 # Implement your plain ruby emailing code here with [`TMail`](http://tmail.rubyforge.org/)
228 end
229 end
230
231 after (:deploy, "notifier:email_the_boss")
232
d368ecb @tcopeland Fixed mispeling
tcopeland authored
233 Note the different arguments, essentially it doesn't matter how you send these, strings, symbols or otherwise, they are automagically read through to ascertain what you intended, I could just have easily have written:
de8843d @leehambley More stuff here\!
authored
234
235 after ('deploy', "notifier:email_the_boss")
236
237 The convention here would appear to be, when using a single word namespace, or task name; **pass it as a symbol** otherwise it must be a string, using the colon-separated task notation.
238
239 There are both [before](), and [after]() callbacks that you can use, and there is nothing to stop you interfering with the execution of any method that calls another, take for example that at the time of writing the implementation of `deploy:default` might look something like this:
240
241 namespace :deploy do
49afd26 @groe add missing "do", fix syntax error
groe authored
242 task :default do
de8843d @leehambley More stuff here\!
authored
243 update
244 update_code
245 strategy.deploy!
246 finalize_update
247 symlink
248 restart # <= v2.5.5
249 end
250 end
251
252 **More Info:** [Default Execution Path on the Wiki](http://wiki.capify.org/index.php/Default_Execution_Path)
253
254 Here we could inject a task to happen after a symlink, but before a restart by doing something like:
255
256 after("deploy:symlink") do
257 # Some more logic here perhaps
258 notifier.email_the_boss
259 end
260
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
261 Which, unless we need the `# Some more logic here perhaps` part could be simplified to:
de8843d @leehambley More stuff here\!
authored
262
263 after("deploy:symlink", "notifier:email_the_boss")
264
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
265 The first example shows the [shorthand anonymous-task syntax](http://wiki.capify.org/index.php/After#.26block).
de8843d @leehambley More stuff here\!
authored
266
267 ##### Calling Tasks
268
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
269 In the examples we have covered how to call tasks on the command line, how to call tasks explicitly in other tasks, and how to leverage the power of callbacks to inject logic into the default deploy strategy. The same techniques of before() and after() callback usage, and your own tasks and namespaces will become important once you start to get beyond the default deployment steps.
270
271 When calling tasks on the command line, most never have to go further than the standard `cap deploy` call; this as you can see from the example above, actually calls a lot of tasks internally, but there is nothing to stop you calling these individually; most rely on other steps, or having queried your choice of `source control` to get the latest revision, but some can be called directly, consider some of the following:
272
273 $ cap deploy:symlink # re-run the method to symlink releases/<tag> to current/
274
275 The trivial example above directly calls one task from a namespace from the command line, another more useful example of this might be:
276
277 namespace :logs do
278 task :watch do
279 stream("tail -f /u/apps/example.com/log/production.log")
280 end
281 end
282
283 Which you could then call with:
284
285 $ cap logs:watch
286
287 Nothing restricts you calling namespaced tasks directly except their potential data prerequisites.
288
289 Another interesting, and often overlooked way of invoking tasks on the command line comes in the form of:
290
291 $ cap task1 task2 namespace1:task1
292
293 Which would call, `task1`, `task2`, `namespace1:task1` in order. You can really make use of this; for example you may want to do something like the following to deploy your app, and immediately follow the logs looking for problems.
294
295 $ cap deploy logs:watch
296
297 A more interesting application for this technique comes in the form of the [Multi-Stage Extension](weblog.jamisbuck.org/2007/7/23/capistrano-multistage), which qualifies for its own section of the handbook; we'll discuss a simpler implementation briefly here.
298
299 The Multi-Stage Extension is designed for deploying the same application to multiple `stages` (development, preview, staging, production, etc) and is usually invoked as such:
300
301 $ cap production deploy
302 $ cap production logs:watch
303 $ cap staging deploy
304 $ cap staging deploy:rollback logs:watch
305
306 The Multi-Stage Extension may be implementing something like the following internally:
307
2fa2a3c @leehambley Finished writing about variables, there wasn't much to say\!
authored
308 set :application, 'example-website'
309
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
310 task :production do
2fa2a3c @leehambley Finished writing about variables, there wasn't much to say\!
authored
311 set :deploy_to, "/u/apps/#{application}-production/"
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
312 set :deploy_via, :remote_cache
313 after('deploy:symlink', 'cache:clear')
314 end
315
316 task :staging do
2fa2a3c @leehambley Finished writing about variables, there wasn't much to say\!
authored
317 set :deploy_to, "/u/apps/#{application}-staging/"
917f6ad @leehambley Finished writing about tasks, except task transactions
authored
318 set :deploy_via, :copy
319 after('deploy:symlink', 'cruise_control:build')
320 end
321
322 When you call `cap production deploy`, two variables are set to production friendly values, and an callback is added to clear the live cache (however that might need to work for your environment), where when you call `cap staging deploy` those same two variables are given different values, and a different callback is registered to tell your imaginary [Cruise Control](http://cruisecontrol.sourceforge.net/) server to rebuild and/or test the latest release.
323
324 The example above is trivial, but that should explain in a nut shell how the Multi-Stage Extension functions, and how you can implement your own quite easily; The Multi-Stage Extension is still well worth a look, as it is smart about ensuring you don't just run `cap deploy` and get yourself into trouble deploying an application with half of your configuration missing
de8843d @leehambley More stuff here\!
authored
325
326 ##### Transactions
327
feaecd5 @leehambley Finished writing about tasks completely now, barring any niggling red…
authored
328 Transactions are a powerful feature of Capistrano that are sadly under-used, *what would happen if your deploy failed?*
329
330 Transactions allow us to define what should happen to roll-back a failed task, take a look at the following example:
331
332 task :deploy do
333 transaction do
334 update_code
335 symlink
336 end
337 end
338
339 task :update_code do
340 on_rollback { run "rm -rf #{release_path}" }
341 source.checkout(release_path)
342 end
343
344 task :symlink do
345 on_rollback do
346 run <<-EOC
347 rm #{current_path};
348 ln -s #{previous_release} #{current_path}
349 EOC
350 end
351 run "rm #{current_path}; ln -s #{release_path} #{current_path}"
352 end
353
354 Before `deploy:symlink` is run, the only thing required to roll-back the changes made by `deploy:update_code` is to remove the latest release.
355
356 In the `deploy:update_code` example, only one step is needed to undo the *damage* done by the failed task, for `deploy:symlink` there is a little more to it, and in this example this is implemented using the `do..end` block syntax also using a [heredoc](http://en.wikipedia.org/wiki/Heredoc#Ruby) to pass a multi-line string to the run() command, in this instance, as you can see it removes the `current` symlink and replaces it with one to the `previous_release`.
357
358 If your roll-back logic was any more complicated than that, you may consider including a rake task with your application with some kind of rollback task that you can invoke to keep the deployment simple.
2fa2a3c @leehambley Finished writing about variables, there wasn't much to say\!
authored
359
360 #### Variables
361
362 Capistrano has its own variable mechanism built in, you will not in the default `deploy.rb` that `capify` generates most of the variable assignment is done in the following manner:
363
364 set :foo, 'bar'
365
366 As [`set`](http://wiki.capify.org/index.php/Set) is quite a complex function, we will only brush the surface here.
367
368 Here are a few things to note:
369
370 set :username, 'Capistrano Wizard'
371
372 task :say_username do
373 puts "Hello #{username}"
374 end
375
376 Note that we have a *real* ruby variable to use in our string interpolation, having used the Capistrano specific `set` method to declare, and assign to it.
377
378 One of the key benefits to using the `set` method is that it makes the resulting variable available anywhere inside the Capistrano environment, as well as being able to assign complex objects such as Procs to variables for delayed processing.
379
380 Set has a partner function [`fetch`](http://wiki.capify.org/index.php/Set) that functions similarly except that it is for retrieving previously `set` variables.
381
382 In addition, there is [`exists?`](http://wiki.capify.org/index.php/Exists%3F) which can be used to check whether a variable exists at all; this might be used to implement a solution to the *missing stage* problem we left unresolved in the **Tasks** section:
383
384 before :deploy do
385 unless exists?(:deploy_to)
386 raise "Please invoke me like `cap stage deploy` where stage is production/staging"
387 end
388 end
389
390 For convenience Capistrano's internals use a method called `_cset` which is designed to non-destructively set variables, it is implemented using `exists?` and `set`, take a look:
391
392 def _cset(name, *args, &block)
393 unless exists?(name)
394 set(name, *args, &block)
395 end
396 end
397
398 This can be used without you having to redefine it to set a variable, only in the event that it hasn't already been set. If you need to change the value of a variable, please just use `set`.
399
400 Part of the argument list to `set` is a `&block`, these can be used to lazy-set a variable, or compute it at runtime... take a look:
401
402 set :application, 'example-website'
403 set :deploy_to, { "/u/apps/#{application}-#{stage}" }
404
405 task :production do
406 set :stage, 'production'
407 end
408
409 task :staging do
410 set :stage, 'staging'
411 end
412
413 Note that on the second line of the example the `stage` variable doesn't exist, and were Capistrano to evaluate this inline, an exception would be raised.
414
415 However, as the `deploy_to` variable isn't used until further through the deployment process, in `deploy:update`, which we know when invoked with `cap production deploy` will run after the `production` task has defined the `stage` variable, the block that is assigned to `:deploy_to` won't be evaluated until then; this is often used by people who wish to have Capistrano ask for their passwords at deploy-time, rather than commit them to the source repository, for example:
416
417 set(:user) do
418 Capistrano::CLI.ui.ask "Give me a ssh user: "
419 end
420
421 This prompt won't be displayed until the variable is actually required, which of course depending on the configuration of your callbacks, may be never at all, this is a very valuable feature that can help ensure your low-level staff or colleagues don't have access to sensitive passwords for production environments that you may wish to keep a secret.
422
d368ecb @tcopeland Fixed mispeling
tcopeland authored
423 **Note:** The curly-brace, and do..end syntaxes are purely a matter of taste and readability, choose whichever suits you better, this is Ruby syntax sugar, and you may use it as you please.
424
Something went wrong with that request. Please try again.