Deploy over SSH

1 month ago1 min read
Last updated • Read time
Cloud
This document is applicable to CircleCI Cloud
Server v4+
This document is applicable to CircleCI Server v4+

In this how-to guide, you will learn how to configure CircleCI to deploy your application over SSH.

1. Add SSH key for target

Add the SSH key for the target to which you are deploying (these instructions are for cloud, server v3.x, and server v4.x).

  1. In a terminal, generate the key with ssh-keygen -t ed25519 -C "your_email@example.com". See Secure Shell documentation for additional details.

  2. In the CircleCI application, go to your project’s settings by clicking the Project Settings button (top-right on the Pipelines page of the project).

  3. On the Project Settings page, click on SSH Keys.

  4. Scroll down to the Additional SSH Keys section.

  5. Select Add SSH Key.

  6. In the Hostname field, enter the key’s associated host (for example, git.heroku.com). If you do not specify a hostname, the key will be used for all hosts.

  7. In the Private Key field, paste the SSH key you are adding.

  8. Select Add SSH Key.

For additional context, see the Adding an SSH Key to CircleCI page.

2. Add the SSH username and hostname

Add the SSH username and SSH hostname of your build VM as environment variables. For instructions, see the Set an environment variable in a project page. In this example, these variables are defined as SSH_USER and SSH_HOST, respectively.

3. Create a deploy job

In your .circleci/config.yml, create a deploy job and add a command to deploy the main branch.

version: 2.1

jobs:
  build:
  #...
  deploy:
    machine:
      image: ubuntu-2204:2023.07.2
    steps:
      - run:
          name: Deploy Over SSH
          command: |
            ssh $SSH_USER@$SSH_HOST "<remote deploy command>"

workflows:
  build-and-deploy:
    jobs:
      - build
      - deploy:
          requires:
            - build # only deploy once build job has completed
          filters:
            branches:
              only: main # only deploy on the main branch