..

Deploy TravisCI builds via SSH

I could not find information about doing it in one place, so I decided to gather all info needed and make a post of it.

We will need to encrypt the private key and bind it to your repo in TravisCI and register the public key to your remote VPS. When it is saved there, the build bot can securely access it while it’s needed.

Requirements (local machine)

  • ruby-dev: apt-get install ruby-dev
  • travis: gem install travis

Generating SSH key and pushing it to Travis CI

  1. Go to the directory of your repository and sudo travis login --com (com if your repo is private and you are using travis.com and not travis.org, otherwise use org)

    When you have enabled 2FA on your GitHub account, you will need to generate token and provide it like this:

    sudo travis login --com --github-token <YOUR TOKEN HERE>

  2. Generate SSH key: ssh-keygen -t rsa -b 4096 -C '[email protected]' -f ./deploy_rsa (create key without password)

  3. Encrypt private key and add it to travis: sudo travis encrypt-file deploy_rsa -add

  4. Copy public key to the destination server and add it to authorized keys: ssh-copy-id -i deploy_rsa.pub [email protected]

  5. Remove deploy_rsa from your repository! Everyone with this key can get access to your server without a password!

  6. Add the following lines to your .travis.yml:

    before_deploy:
    - openssl aes-256-cbc -K $encrypted_?_key -iv $encrypted_?_iv -in deploy_rsa.enc -out /tmp/deploy_rsa -d
    - eval "$(ssh-agent -s)"
    - chmod 600 /tmp/deploy_rsa
    - ssh-add /tmp/deploy_rsa
       
    deploy:
    - provider: script
      skip_cleanup: true
      script: scp -r ./directory_to_copy [email protected]:/dest/dir
       
    addons:
      ssh_known_hosts:
        - hostip
    

    Where ? in encrypted keys, look at Settings->Environment Variables of your repository in Travis

  7. Now all succeeded builds will be deployed