Search code examples
gitdocker.net-coreazure-devops-pipelines

Why won't Azure Devops Pipelines Docker Build stamp my commit version into my dotnet core assembly correctly?


I found Scott Hanselman's tutorial on adding git commit hashes to builds using dotnet. I have tried to adopt his approach in my own project which is being built into Docker images in Azure Devops Pipelines. Unfortunately the git hash never makes it into the assembly.

In my docker file I have:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base

ARG SOURCE_REVISION_ID

WORKDIR /app
RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /usr/lib/ssl/openssl.cnf

EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src

RUN dotnet restore "Project/Project.csproj"
COPY . .
WORKDIR "/src/Project"
RUN dotnet build "Project.csproj" -c Release -o /app/build /p:SourceRevisionId=${SOURCE_REVISION_ID}

FROM build AS publish
RUN dotnet publish "Project.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Project.dll"]

The call to dotnet build "Project.csproj" uses the /p:SourceRevisionId=${SOURCE_REVISION_ID} argument as described in Scott's post.

I have discrete steps in my pipeline for the Build and Push docker agents as I found elsewhere that --build-args are not passed to Docker in a combined BuildAndPush job. I can see that the pipeline is passing the correct SOURCE_REVISION_ID to the build job, e.g. --build-arg SOURCE_REVISION_ID=7397bf9c2650e6cd9452f5c40c6e1738fbb32532.

I suspect one of a few things is the cause but I'm unsure which:

  1. I am using incorrect syntax to retrieve the value of the SOURCE_REVISION_ID argument in my call to dotnet build.
  2. I have misunderstood the difference between ARG and ENV in Dockerfile and need to copy the value of my build argument to a variable for use later. If this is the case, I don't understand why.
  3. Actually it's working fine, but my code isn't extracting the AssemblyInformationalVersion from the assembly correctly (despite my copy and pasting of code from Scott's post!)

Please, help stop me from going bald!


Solution

  • You're using a multi-stage Dockerfile and specified the ARG in the first stage but actually reference it in the second stage. An ARG is scoped to the stage that it's contained in. You should move the ARG to the second stage, after FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build.