This article is about Codeship Pro.

Setting an SSH Private Key

You will need roughly 2 minutes to read this article.

This task requires the following:

Many operations require the configuration of an SSH private key within your container(s) (e.g, git clone, rsync, ssh, etc).

While the task seems as simple as copying a private key right into your Docker image, this is considered highly inadvisable.

The suggested practice is to:

1. Generate & Store SSH Private Key to the Designated Encrypted Env Vars File

Run the following set of commands in the root of your project folder:

# generate codeship_deploy_key and, configured to not require passphrase
docker run -it --rm -v $(pwd):/keys/ codeship/ssh-helper generate "<YOUR_EMAIL>" && \
# store codeship_deploy_key as one liner entry into codeship.env file under `PRIVATE_SSH_KEY`
docker run -it --rm -v $(pwd):/keys/ codeship/ssh-helper prepare && \
# remove original private key file
rm codeship_deploy_key && \
# encrypt file
jet encrypt codeship.env codeship.env.encrypted && \
# ensure that `.gitignore` includes all sensitive files/directories
docker run -it --rm -v $(pwd):/app -w /app ubuntu:16.04 \
/bin/bash -c 'echo -e "codeship.aes\ncodeship_deploy_key\\ncodeship.env\n.ssh" >> .gitignore'

Check out the README page for more information on our SSH Helper tool.

2. Configure your Codeship config files with the following as guidance

# Dockerfile

FROM ubuntu:16.04

RUN apt-get update && apt-get install -y ssh
# codeship-services.yml

    image: codeship/setting-ssh-key-test
    dockerfile: Dockerfile
  encrypted_env_file: codeship.env.encrypted
  # mapping to `.ssh` directory ensures that `id_rsa` file persists to subsequent steps
  # replace container pathing if $HOME is not `/root`
    - ./.ssh:/root/.ssh
# codeship-steps.yml

- name: reinstate SSH Private Key File
  service: app
  command: /bin/bash -c "echo -e $PRIVATE_SSH_KEY >> /root/.ssh/id_rsa"

- name: chmod id_rsa
  service: app
  command: chmod 600 /root/.ssh/id_rsa

- name: add server to list of known hosts
  service: app
  command: /bin/bash -c "ssh-keyscan -H >> /root/.ssh/known_hosts"

- name: confirm ssh connection to server, authenticating with generated public ssh key
  service: app
  command: /bin/bash -c "ssh -T 2>&1 | grep 'successfully authenticated'"

If you’re still largely unfamiliar with the nuts and bolts of Codeship Pro, then check out our step-by-step, from the ground up walk-through on setting up a private ssh key

Need more help?

You can post on Stack Overflow using the tag #codeship or contact our Helpdesk.
We also have a couple of code examples and sample projects available for you to get started with.

Article not helpful?

Do you think we need to improve this article? If so, please submit our feedback form to help us improve this article!