Search code examples
.net-corenugetazure-devopscakebuild

How do you restore private NuGet packages from private VSTS feeds with Cake


I have a task which restores our NuGet package for our dotnet core application:

Task("Restore-Packages")
    .Does(() =>
{
    DotNetCoreRestore(sln, new DotNetCoreRestoreSettings {
        Sources = new[] {"https://my-team.pkgs.visualstudio.com/_packaging/my-feed/nuget/v3/index.json"},
        Verbosity = DotNetCoreVerbosity.Detailed
    });
});

However when run on VSTS it errors with the following:

2018-06-14T15:10:53.3857512Z          C:\Program Files\dotnet\sdk\2.1.300\NuGet.targets(114,5): error : Unable to load the service index for source https://my-team.pkgs.visualstudio.com/_packaging/my-feed/nuget/v3/index.json. [D:\a\1\s\BitCoinMiner.sln]
2018-06-14T15:10:53.3857956Z        C:\Program Files\dotnet\sdk\2.1.300\NuGet.targets(114,5): error :   Response status code does not indicate success: 401 (Unauthorized). [D:\a\1\s\BitCoinMiner.sln]

How do I authorize access for the build agent to our private VSTS?


Solution

  • I literally just had this same problem, apparently the build agents in VSTS can't get to your private VSTS feed without an access token so you are going to have to create a Personal Access Token in VSTS and provide that to the built in Cake method to add an authenticated VSTS Nuget feed as one of the sources. Here, I have wrapped it in my own convenience Cake method that checks to see if the package feed is already present, if not, then it adds it:

    void SetUpNuget()
    {
        var feed = new
        {
            Name = "<feedname>",
            Source = "https://<your-vsts-account>.pkgs.visualstudio.com/_packaging/<yournugetfeed>/nuget/v3/index.json"
        };
    
        if (!NuGetHasSource(source:feed.Source))
        {
            var nugetSourceSettings = new NuGetSourcesSettings
                                 {
                                     UserName = "<any-odd-string>",
                                     Password = EnvironmentVariable("NUGET_PAT"),
                                     Verbosity = NuGetVerbosity.Detailed
                                 };     
    
            NuGetAddSource(
                name:feed.Name,
                source:feed.Source,
                settings:nugetSourceSettings);
        }   
    }
    

    and then I call it from the "Restore" task:

    Task("Restore")
        .Does(() => {       
            SetUpNuget();
            DotNetCoreRestore("./<solution-name>.sln"); 
    });
    

    Personally, I prefer to keep PATs away from the source control so here I am reading from env vars. In VSTS you can create an environment variable under the Variables tab of your CI build configuration.

    enter image description here

    Hope this helps! Here is a link to Cake's documentation.