Search code examples
sshgithub-actionsportforwardingcicd

Port forwarding in CICD (Github Actions)


I want to run db migrations in Github Actions. The DB is behind a bastion.

My solution was to forward Postgres port 5432 to the db host through the bastion.

I tried below script but does not seem to work.

mkdir ~/.ssh
ssh-keyscan -H <bastion_ip>  >> ~/.ssh/known_hosts
echo "${{secrets.BASTION_SSH_KEY}}" >> key
chmod 600 ./key
ssh -T -i ./key -L 5432:<db_host_url>:5432 user@<bastion_ip> &
make migrate
rm ./key

make migrate runs migration against localhost:5432.

When I run the pipeline I get following error

Error:  AssertionError [ERR_ASSERTION]: ifError got unwanted exception: connect ECONNREFUSED 127.0.0.1:5432

Anyway to fix it? I am open to other ways of doing it.


Solution

  • Thanks @larsks, I got it working. There were a couple of things I had to change to get it working.

    1. added -fN as suggested by @larsks
    2. used ssh-agent to handle the key

    Below is the working code snippet:

    mkdir ~/.ssh
    ssh-keyscan -H <bastion_ip> >> ~/.ssh/known_hosts
    eval `ssh-agent -s`
    ssh-add - <<< "${{secrets.BASTION_SSH_KEY}}"
    ssh -fN -v -L 5432:<db-host>:5432 user@<bastion_ip>
    make migrate