Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save erikmd/ba9edc8bf0919287b6291ca4b6449864 to your computer and use it in GitHub Desktop.
Save erikmd/ba9edc8bf0919287b6291ca4b6449864 to your computer and use it in GitHub Desktop.
[Ubuntu] Deploy a docker-compose from Github Actions using SSH

1. Create SSH keypair

In order to deploy using SSH, we need a SSH keypair. Please use an algorithm strong enough and also supported by GHA and your remote host.

You can use the command below to generate a keypair:

ssh-keygen -t ed25519 -C gha@vm-YourLogin -f ~/.ssh/id_gha

For this use case, don't use a passphrase (just type Return to select an empty passphrase).

The fresh value for option -f ensures it won't overwrite an existing key file.

The value for option -C is an optional identifier that allows you to remember what the key is for (here, just for the GHA job to ssh into your vm).

This command will generate 2 files:

  • id_gha.pub : this is the public key (can be given to anyone)
  • id_gha : this is the private key.

2. Setup the remote

Log into your remote host. Create a user named gha and assign him to the docker group.

Then, execute the commands below (please, replace 〈PUBLIC_KEY〉 with the public key created previously):

sudo su
su gha
cd
mkdir -m 700 .ssh
cd .ssh
touch authorized_keys
echo "〈PUBLIC_KEY〉" >> authorized_keys
exit

3. Setup GitHub repository

Log into GitHub and go to your repository. Then, go to Settings > Secrets and variables > Actions > New repository secrets. Create a new secret and name it GHA_DEPLOY_SSH_PRIVATE_KEY, then paste the private key in the value.

4. Deploy with GitHub Actions

Use a workflow like this one to deploy with docker-compose. Please, replace 〈HOSTNAME〉 with your VM's domain name.

name: Deploy
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: webfactory/ssh-agent@v0.5.4
        with:
          ssh-private-key: ${{ secrets.GHA_DEPLOY_SSH_PRIVATE_KEY }}
          
      - name: Disable Host key verification
        # Hack to prevent "Host key verification failed". Should be replaced with a ssh-keyscan based solution
        run: echo "StrictHostKeyChecking no" >> ~/.ssh/config

      - name: Deploy
        run: docker-compose up -d
        env:
          COMPOSE_DOCKER_CLI_BUILD: 0
          DOCKER_HOST: "ssh://gha@〈HOSTNAME〉"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment