Skip to main content

Command Palette

Search for a command to run...

How to use private go module in GitHub Actions

Keep your private go modules organized

Updated
2 min read
How to use private go module in GitHub Actions

Sometimes you may want to keep your go modules private and separated in a private GitHub repository. Here I will show you how to setup your GitHub actions to use a private go module hosted on GitHub.

TLDR: Create a personal access token, set a git config to use the token when pulling from GitHub and set the go module as private.

Setup a personal access token

Go to https://github.com/settings/tokens and generate a new token.

generate token step 1

Give it a name and make sure to select repository scope.

generate token step 2

Then go to your project's settings page, click on Secrets and add a new repository secret.

add secret step 1

Give it a name and paste the token generated before.

add secret step 2

Setup your GitHub Action

Add an environment variable to tell go that this go module is private:

jobs:
  run:
    runs-on: ubuntu-latest
    env:
+     GOPRIVATE: github.com/fabianMendez/privatemodule
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-go@v2
        with:
            go-version: '1.16'
      - run: go build

Add your access token as an environment variable taken from your secret.

jobs:
  run:
    runs-on: ubuntu-latest
    env:
      GOPRIVATE: github.com/fabianMendez/privatemodule
+     GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }}
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-go@v2
        with:
            go-version: '1.16'
      - run: go build

Finally, run this command so that git uses your token when pulling repositories from GitHub:

jobs:
  run:
    runs-on: ubuntu-latest
    env:
      GOPRIVATE: github.com/fabianMendez/privatemodule
      GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }}
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-go@v2
        with:
            go-version: '1.16'
+     - run: git config --global url.https://$GH_ACCESS_TOKEN@github.com/.insteadOf https://github.com/
      - run: go build

That's it

With this you can better organize your private go modules and unlock the power of GitHub Actions.

I hope this was useful to you.