.net 使用Gitlab CI发布Nuget包

7eumitmz  于 2023-05-02  发布在  .NET
关注(0)|答案(1)|浏览(210)

我已经遵循了这个tutorial关于如何创建一个nuget工具包。
现在我想在Gitlab Pipeline中创建标签时部署这个包:

stages:
  - build
  - deploy

variables:
  PACKAGE_SOURCE:
    value: https://api.nuget.org/v3/index.json
    description: Specifies the Nuget package server URL.

image: mcr.microsoft.com/dotnet/sdk:7.0

build-job:
  stage: build
  script:
  - dotnet build -c Release
  artifacts:
    untracked: true

package-job:
  stage: build
  needs:
    - job: build-job
      artifacts: true
  script:
  - dotnet pack -c Release --no-build --output nupgk
  artifacts:
    paths:
      - nupgk

deploy-job:
  stage: deploy
  only:
  - tags
  needs:
    - job: package-job
      artifacts: true
  script:
  - echo "Pushing package to $PACKAGE_SOURCE"
  - dotnet nuget push nupgk/*.nupkg --api-key "$PACKAGE_SERVER_TOKEN" --source "$PACKAGE_SOURCE"

构建作业和打包工作正常,然后在部署作业中(当我将标记推送到存储库时),我得到以下消息:

$ echo "Pushing package to $PACKAGE_SOURCE"
Pushing package to https://api.nuget.org/v3/index.json

$ dotnet nuget push nupgk/*.nupkg --api-key "$PACKAGE_SERVER_TOKEN" --source "$PACKAGE_SOURCE"
warn : No API Key was provided and no API Key could be found for 'https://www.nuget.org/api/v2/package'. To save an API Key for a source use the 'setApiKey' command.
Pushing mypackage.myversion.nupkg to 'https://www.nuget.org/api/v2/package'...
  PUT https://www.nuget.org/api/v2/package/
  Unauthorized https://www.nuget.org/api/v2/package/ 570ms
error: Response status code does not indicate success: 401 (An API key must be provided in the 'X-NuGet-ApiKey' header to use this service).

我不理解这种行为,因为当我在本地机器上运行完全相同的命令(使用相同的docker镜像)时,我会得到以下输出:

$ echo "Pushing package to $PACKAGE_SOURCE"
Pushing package to https://api.nuget.org/v3/index.json

$ dotnet nuget push nupgk/*.nupkg --api-key "$PACKAGE_SERVER_TOKEN" --source "$PACKAGE_SOURCE"
Pushing mypackage.myversion.nupkg to 'https://www.nuget.org/api/v2/package'...
  PUT https://www.nuget.org/api/v2/package/
  Created https://www.nuget.org/api/v2/package/ 1090ms
Your package was pushed.

似乎dotnet nuget完全忽略了我的来源论点,我也不知道为什么。

3npbholx

3npbholx1#

好吧,这似乎是管道配置之外的问题。事实证明,Gitlab默认情况下将变量设置为protected(我将其与masked混淆)。这意味着PACKAGE_SERVER_TOKEN变量在标记管道上不可用,因为标记本身在创建时没有受到保护。
修复:我添加了一个通配符标记保护规则v*来创建一个受保护的标记,并额外修改了管道,使其仅在引用受保护时运行(以确保在创建作业时设置变量)

...
deploy-job:
  stage: deploy
  only:
    refs:
      - tags
    variables:
      - $CI_COMMIT_REF_PROTECTED
...

相关问题