Notes to self

How to use private SSH keys with passwords in GitHub Actions

Most people opt for going with a passwordless key for their CI/CD pipeline, but what if you want to keep the password?

GitHub secrets

Let’s start by adding our SSL private key as a secret. If you don’t have one yet, create it:

$ ssh-keygen -t ed25519 -C "ci@domainplaceholder.com"

Adding a new private SSH key to be used in a GitHub action is same as adding it as any other secret.

Navigate to your repository Settings and then select Actions under Secrets and variables. Here you can add new secrets for GitHub Actions that will be made available in your workflows.

If we’ll add SSH_PRIVATE_KEY, then this will be available as ${{secrets.SSH_PRIVATE_KEY}}.

Similarly if we want to store a password to the key, adding SSH_PASSPHRASE secret will be made available as ${{secrets.SSH_PASSPHRASE}}.

We can now use this in our actions.

Passwordless key

If your SSH key doesn’t have a password, there is a nice premade ssh-agent action:

jobs:
  deploy:
    name: Deploy
    steps:
      - name: Setup SSH
        uses: webfactory/ssh-agent@v0.7.0
          with:
            ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

By passing our private secret we are basically done. The action will add our private key to the SSH agent.

Using a password

If on the other hand we have a key with a password, we need to provide it ourselves to the ssh-agent. To do that we can temporarily save it into a file and then provide it with SSH_ASKPASS variable:

env:
  # Use the same ssh-agent socket value across all jobs
  SSH_AUTH_SOCK: /tmp/ssh_agent.sock

jobs:
  deploy:
    name: Deploy
    steps:
      - name: Setup SSH with a passphrase
        env:
          SSH_PASSPHRASE: ${{secrets.SSH_PASSPHRASE}}
          SSH_PRIVATE_KEY: ${{secrets.SSH_PRIVATE_KEY}}
        run: |
          ssh-agent -a $SSH_AUTH_SOCK > /dev/null
          echo "echo $SSH_PASSPHRASE" > ~/.ssh_askpass && chmod +x ~/.ssh_askpass
          echo "$SSH_PRIVATE_KEY" | tr -d '\r' | DISPLAY=None SSH_ASKPASS=~/.ssh_askpass ssh-add - >/dev/null

And that’s it, our key will be added and shared for out workflow jobs.

Check out my book
Deployment from Scratch is unique Linux book about web application deployment. Learn how deployment works from the first principles rather than YAML files of a specific tool.
by Josef Strzibny
RSS