Capistrano is a tool used for remote server automation and deployment, written in Ruby. It uses SSH to connect with server for performing various operations and Rake to define tasks required to perform deployment on a specific server. To automate repetitive deployment tasks, it can also be used for any language or framework including Java, PHP, Rails, etc.
Additionally, you can write your own automated deployment scripts by writing rake tasks. However, Capistrano provides a basic structure for multiple plugins to deploy them easily. Following is it’s file structure:
│ ├── deploy
│ │ ├── production.rb
│ │ └── staging.rb
│ └── deploy.rb
Here, Capfile is used to require plugin files and define user defined rake tasks. Config/Deploy is a directory where environment (staging/production) specific files are placed for the server. Deploy.rb file is used to define generic variables, configurations, and tasks, etc. Additionally, Lib/Capistrano/Tasks is a directory where user defined custom rake tasks for capistrano are placed.
Setup in Ruby on Rails
In a project’s Gemfile, specify “capistrano” as a core gem and any other gem like “capistrano-rails” to provide extended core functionality.
To add extra functionality in Capfile, “capistrano-rails” gem is required here. Add the following line of code to import the required gem:
To create capistrano recipe in deploy.rb file, set the following variables used by capistrano for all environments:
To create capistrano recipe in config/deploy/production.rb file, set environment specific variables (production in the following case):
Here, “serverIP_or_domain” is the IP address or domain name that the client machine uses to connect with server and for its deployment.
Tasks that are shared among all environments are placed in deploy.rb file like variables while environment specific tasks are placed in their respective environment files (for example, tasks of production environment will be placed in config/deploy/production.rb file).
The following two tasks are presented as an example of rake tasks having Capistrano DSL support.
- This example is used for checking the access to a specified server.
- The example is used for checking whether Git local branch is synced with remote branch or not.