Tuesday, January 11, 2022

Github - Deploy a Nuget Package on a new release

I have a small library that I created a few years ago to use PostgreSQL as a distributed cache in .NET core.

As I wanted to get more acquainted with Github and all it possibilities, I thought it was a good occasion to make some improvements and optimize the deployment process. (I manually pushed the first version of the package to NuGet.org).

Let’s see how we can automate this by combining the Release functionality in Github with Github actions.  

Create the Github actions workflow

Let’s first create a workflow that does the following:

  • Build the library
  • Create the NuGet package
  • Upload the NuGet package to NuGet.org

Therefore we go to our Github page and select Actions.

Choose New workflow.

We will not use one the suggested workflows but want to create our workflow from scratch so click on set up a workflow yourself.

Now we’ve finally arrived on the Edit workflow screen.

Replace the existing workflow definition with the following:

What is important to notice in the workflow above:

  • The workflow is triggered when we publish a new release(more about this later)
  • We use the tag_name value that can be specified during a release to update the package version:

dotnet pack --configuration Release --no-restore /p:Version=${{ github.event.release.tag_name }}

  • The api key required to push our package to NuGet.org is managed outside the workflow and stored as a Github secret using ‘NUGET_API_SECRET’ as its name:

dotnet nuget push **/*.nupkg --api-key ${{ secrets.NUGET_API_SECRET }} --source https://api.nuget.org/v3/index.json

Set the secret

To set the secret we need to go to Settings.

There we need to go the Secrets section and create a new secret using the New repository secret button.

Specify a name(in this case NUGET_API_SECRET) and a value:

Create a release

Now we can finally create a release. On the home page of your repo click on Releases on the right.

On the Releases page, click on the Draft a new release button.

Hit Choose a tag and enter a new release number here e.g. 2.0.2. What is important here is that this number is a valid NuGet package version number because it is this tag value that will be used inside our workflow.

Click on Publish release.

This should trigger the workflow and after a few minutes, you should see a succesfull run of the workflow on the Actions tab.