How to run a SonarCloud scan during Docker builds for .NET Core
How to kick-off a SonarCloud scan during a build of a .NET Core Docker container.
SonarCloud is one of the most popular solutions for static code analysis in the context of modern DevOps processes. Here is how to kick-off a SonarCloud scan during a build of a .NET Core Docker container.
In your Dockerfile
, make sure to add some arguments for variables like SONAR_PROJECT_KEY
that can be replaced for every build later. Also, install the required components for a SonarCloud scan. For .NET Core, there are currently Java and the dotnet-scanner tool.
ARG SONAR_PROJECT_KEY=robinmanuelthiel_microcommunication
ARG SONAR_OGRANIZAION_KEY=robinmanuelthiel
ARG SONAR_HOST_URL=https://sonarcloud.io
ARG SONAR_TOKEN
# Install Sonar Scanner, Coverlet and Java (required for Sonar Scanner)
RUN apt-get update && apt-get install -y openjdk-11-jdk
RUN dotnet tool install --global dotnet-sonarscanner
RUN dotnet tool install --global coverlet.console
ENV PATH="$PATH:/root/.dotnet/tools"
Next, start the Sonar scanner. Make sure, to do this, before you start building the .NET Core app.
# Start Sonar Scanner
RUN dotnet sonarscanner begin \
/k:"$SONAR_PROJECT_KEY" \
/o:"$SONAR_OGRANIZAION_KEY" \
/d:sonar.host.url="$SONAR_HOST_URL" \
/d:sonar.login="$SONAR_TOKEN" \
/d:sonar.cs.opencover.reportsPaths=/coverage.opencover.xml
Now you can start your build and tests. Once the build is completed, stop the Sonar scanner and upload the results.
# End Sonar Scanner
RUN dotnet sonarscanner end /d:sonar.login="$SONAR_TOKEN"
When building the Docker image, make sure to pass your SONAR_TOKEN
and other build arguments to the docker build
command.
docker build . --build-arg SONAR_TOKEN=xxxxxxxxxxx
You can find an example of a full Dockerfile
below, that builds a .NET Core app in a container and runs a SonarCloud analysis during the build. You can build the image by passing
☝️ Advertisement Block: I will buy myself a pizza every time I make enough money with these ads to do so. So please feed a hungry developer and consider disabling your Ad Blocker.