Letting your dependencies get out of date is an all too common problem. On the face of it, you might think it’s not such a big issue – “our code works, why do we need to worry?”.
However, keeping on top of your updates on a regular basis has several advantages:
- It is one of the easiest ways to minimise the risk of security vulnerabilities. Vulnerabilities are often discovered in popular (or not so popular) packages. New releases are produced to fix these vulnerabilities.
- You reap the benefits of any bug fixes or optimisations that have been introduced.
- Frequent, small changes are easier to manage and carry less risk than allowing changes to back up and become big changes.
With a little preparation, keeping on top of this is pretty easy. The dotnet command has inbuilt support for checking for outdated packages. Simply execute the following while in your solution or project directory:
dotnet list package --outdated
This will check the package versions requested in your project(s) and output a list of any package for which a later version is available.
One thing worth noting is that you need to have done a 'restore' on the project(s) before running this check because it requires the projects.assets.json file to have been generated and be up to date.
There are a few ways that the behaviour of this check can be modified. For example, restricting the check to minor versions. You can find full details in the Microsoft dotnet list package docs.
So far so good, but what if we want to enforce updates in the CI/CD pipelines? We can achieve this by wrapping the command in a Bash script that will return a non-zero exit code if outdated dependencies are detected. I’ve recently used this in Azure DevOps pipelines, but the same technique will apply to other pipeline tools.
The script I used is here:
#!/bin/bash updates=$(dotnet list package --outdated | grep -e 'has the following updates') if [[ -n "$updates" ]]; then dotnet list package --outdated echo "##[error]Outdated NuGet packages were detected" exit 1 else echo "No outdated NuGet packages were detected" exit 0 fi
It simply looks for the text “has the following updates” in the output from calling
dotnet list package --outdated and if that phrase is present, exits with the non-zero return code. The
##[error] tag is an Azure DevOps Pipeline feature which means the echoed message will be formatted as an error (i.e. appear in red) in the pipeline log details.