How to push to another repo from github actions

2023-11-15 linux

Here's how to push to another Git repository from GitHub using GitHub Actions(workflow).

Preparation

First of all, need to create RSA key pair and register it as secrets(from Settings). Also need to register the value of known_hosts to the target host.

key: ${{ secrets.ID_RSA }}
known_hosts: ${{ secrets.KNOWN_HOSTS }}

Make sure to add the public key to target host. So that the action will be able to connect via ssh.

The action

Put the yaml under .github/workflows folder on the project.

name: "Deploy to VPS"
on:
  push:
    branches: [ "main" ]
jobs:
  production:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      - name: Install SSH key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.ID_RSA }}
          known_hosts: ${{ secrets.KNOWN_HOSTS }}
      - name: Add remote
        run: git remote add production user@sample.net:repos/myprj.git
      - name: Unshallow old
        run: git fetch --unshallow
      - name: Push to remote
        run: git push production main

Troubleshoot

If you have troubles to connect to the host, The step may be useful.

- name: Test ssh connection
  run: ssh user@sample.net uptime

Because the checkout@v4 action runs with --depth option, unshallow is required to push the content to another repository.