Max SchmittMS
17th May 2020

How to use an SSH key inside GitHub actions

Yesterday I moved the deployment for this site from a local script to GitHub actions. Overall it was a really pleasant experience because GitHub made it really easy to run scripts inside e.g. a Node.js environment, which I need to build the site.

One thing that was a bit tricky for me, was figuring out how to git push to my Dokku server from GitHub Actions. I needed to authenticate GitHub Actions for SSH access to my Dokku server.

I ended up generating a new SSH key for GitHub Actions and saving the private key to my repository's secrets (find them in the repo settings) as DOKKU_SSH_KEY.

Then I added a few lines to my main.yml file:

name: CI
on:
push:
branches: [master]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js environment
uses: actions/setup-node@v1.4.2
with:
node-version: 12.x
- name: Add SSH key
env:
SSH_AUTH_SOCK: /tmp/ssh_agent.sock
run: |
mkdir -p /home/runner/.ssh
# Replace example.com with the hostname of the machine
# you're SSH-ing into
ssh-keyscan example.com >> /home/runner/.ssh/known_hosts
# DOKKU_SSH_KEY is the name of the repository secret
echo "${{ secrets.DOKKU_SSH_KEY }}" > /home/runner/.ssh/github_actions
chmod 600 /home/runner/.ssh/github_actions
ssh-agent -a $SSH_AUTH_SOCK > /dev/null
ssh-add /home/runner/.ssh/github_actions
- name: Install dependencies
run: yarn
- name: Build and deploy
env:
SSH_AUTH_SOCK: /tmp/ssh_agent.sock
run: |
git config --global user.email "actions@github.com"
git config --global user.name "GitHub actions"
yarn build --env production
git remote add dokku dokku@example.com:app-name
git add dist --force
git commit -m "Deploy"
git push dokku master -f

And that's all it took to get Github Actions authenticated with my Dokku server. I hope this was helpful to you, thanks for reading!


Need help on a project?

I'm available for freelance work.
Send me an email! Or find out more about my services.