Set Assembly version of net core app using Azure DevOps with a DockerFile

Viewed 1695

I am using a DockerFile created by visual studio to create my image. I want to build with Azure DevOps and set my assemblies version inside the image the version I have in the Pipeline. I feel that I have to change this line but I dont known how.

    RUN dotnet build "ImportBatch.Api.csproj" -c Release -o /app/build

My DockerFile

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["ImportBatch.Api/ImportBatch.Api.csproj", "ImportBatch.Api/"]
COPY ["ImportBach.Dto/ImportBatch.Dto.csproj", "ImportBach.Dto/"]
COPY ["Common/Common.csproj", "Common/"]
COPY ["Common.Dto/Common.Dto.csproj", "Common.Dto/"]
COPY ["Common.Azure.Storage/Common.Azure.Storage.csproj", "Common.Azure.Storage/"]
RUN dotnet restore "ImportBatch.Api/ImportBatch.Api.csproj"
COPY . .
WORKDIR "/src/ImportBatch.Api"
RUN dotnet build "ImportBatch.Api.csproj" -c Release -o /app/build

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

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Cardinal.Software.ImportBatch.Api.dll"]
2 Answers

From pipeline:

- task: Docker@1
  displayName: 'Build the image'
  inputs:
    dockerfile: 'Dockerfile'
    imageName: '$(imageRepoName):$(GitVersion.SemVer)'
    arguments: '--build-arg version=$(GitVersion.SemVer)'
  continueOnError: true

On DockerFile:

FROM mcr.microsoft.com/dotnet/sdk:5.0-alpine AS build
WORKDIR /src
COPY . .
ARG version  #define the argument
#use this argument while running build or publish, for example
RUN dotnet publish "./yourProject.csproj" -c Release /p:Version=${version} -o /app/publish --no-restore

For SDK-style projects assembly version attributes are generated automatically, so you can use p:Version=1.2.3.4 right out of the box. Please check example here (at the bottom)

dotnet build -p:Version=1.2.3.4

Related