How do I use a Nuget package in the Artifacts page in my Docker Build step?

Viewed 720

In my Azure Devops project, under the tab "Artifacts", I have a package MyPackage.

enter image description here

In my build pipeline, I have this step:

  - stage: Build
    displayName: "Build"
    jobs:
    - job: 
      steps:
      - task: Docker@2
        inputs:
          containerRegistry: 'TEST container registry'
          repository: 'mycontainerregistry/backend'
          command: 'buildAndPush'
          buildContext: '$(System.DefaultWorkingDirectory)'
          Dockerfile: '**/Dockerfile'
          tags: |
            $(Build.BuildId)
            latest

The Dockerfile being built is the standard generated one by Visual Studio:

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 ["MyProject.API.csproj", "MyProject.API/"]
RUN dotnet restore "MyProject.API/MyProject.API.csproj"
COPY . .
WORKDIR "/src/MyProject.API"
RUN dotnet build "MyProject.API.csproj" -c Release -o /app/build

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

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

Now, the problem is with the dotnet restore command. This step fails because the restore command can't find the MyPackage nuget from the docker build context. How can I make dotnet restore find MyPackage when running through docker build?

1 Answers

If you have private feed you need to add a source using dotnet nuget add source

dotnet  nuget sources add -name "SomeName" -source https://pkgs.dev.azure.com/YourFeed/nuget/v3/index.json -username anything -password $TOKEN

And to pass System.AccessToken you need to use ARG

FROM alpine

ARG TOKEN
RUN dotnet  nuget sources add -name "SomeName" -source https://pkgs.dev.azure.com/YourFeed/nuget/v3/index.json -username anything -password $TOKEN

and then in YMAL

- task: Docker@2
  inputs:
    containerRegistry: 'devopsmanual-acr'
    command: 'build'
    Dockerfile: 'stackoverflow/85-docker/DOCKERFILE'
    arguments: '--build-arg TOKEN=$(System.AccessToken)'

Please split you buildAndPush as it doesn't allow passing arguments into two separate task. For more details please check this question.

Please also make sure that you can Build Service has contributor role on feed settings.

Related