Skip to content

Instantly share code, notes, and snippets.

@seanmarcia
Last active June 12, 2017 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanmarcia/5fe5dde67380514fab25745fd21a67d8 to your computer and use it in GitHub Desktop.
Save seanmarcia/5fe5dde67380514fab25745fd21a67d8 to your computer and use it in GitHub Desktop.
Deploy from Travis to a vps with Capistrano

Setup

On a development machine, install the Travis CLI gem and login.

$ gem install travis
$ travis login

Create a ssh key on your development machine.

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

This command will generate an id_rsa and id_rsa.pub on your machine in a hidden folder in your root directory. ~/.ssh

On your vps ensure that the public key is an authorized key on the server. On your vps cat ~/.ssh/authorized_keys and ensure that id_rsa.pub is listed. If not, add it.

In your rails app, use the travis gem to encrypt your id_rsa

travis encrypt-file ~/.ssh/id_rsa
encrypting id_rsa for ruby/my_app
storing result as id_rsa.enc
storing secure env variables for decryption

Travis will output the decryption information that you need to add into your .travis.yml. The command will look like something like:

openssl aes-256-cbc -K $encrypted_d7f80deb40b0_key -iv $encrypted_d7f80deb40b0_iv -in id_rsa.enc -out config/deploy_id_rsa -d 

Now add a script to the .travis.yml file that will decrypt the key. Your .travis.yml should look something like this if you are only deploying from master:

language: ruby
script:
- export RAILS_ENV=test
- bundle exec rake db:create db:migrate
- bundle exec rake spec
after_success:
- openssl aes-256-cbc -K $encrypted_d7e80deb40b0_key -iv $encrypted_d7e80deb40b0_iv -in id_rsa.enc -out config/deploy_id_rsa -d  
- "[[ $TRAVIS_BRANCH = 'master' ]] && bundle exec cap production deploy"

You also need to update the Capistrano configuration to use the RSA key:

# deploy.rb
set :ssh_options, keys: ["config/deploy_id_rsa"] if File.exist?("config/deploy_id_rsa")

If the Capistrano :ssh_options doesn't work you can manually add the deploy key to the server it in your .travis.yml by doing the following:

language: ruby
script:
- export RAILS_ENV=test
- bundle exec rake db:create db:migrate
- bundle exec rake spec
after_success:
- openssl aes-256-cbc -K $encrypted_d7e80deb40b0_key -iv $encrypted_d7e80deb40b0_iv -in id_rsa.enc -out config/deploy_id_rsa -d  
- "chmod 600 config/deploy_id_rsa"
- "eval `ssh-agent -s`"
- "ssh-add config/deploy_id_rsa"
- "[[ $TRAVIS_BRANCH = 'master' ]] && bundle exec cap production deploy"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment