You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab CI创建Production分支时无法获取密码致dotnet restore失败

GitLab CI构建密码为空问题原因分析

配置文件与问题现象

GitLab CI YAML配置

before_script:  
  - export GITLAB_PACKAGE_REGISTRY_USERNAME="DeployUser"
  - export GITLAB_PACKAGE_REGISTRY_PASSWORD=$DeployPassword
  - dotnet restore ${PROJECT} --packages ./.nuget/ --verbosity quiet

Build and Test:
  stage: build and test
  script:
    - dotnet build ${PROJECT} --no-restore -c Release --verbosity quiet -o out
    Release
  when: always
  only:
    - develop
    - /^Production/[0-9]+(?:.[0-9]+)+$/

nuget.config配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="gitlab" value="https://gitlab.com/api/v4/projects/1234567/packages/nuget/index.json" />
    </packageSources>
    <packageSourceCredentials>
     <gitlab>
         <add key="Username" value="%GITLAB_PACKAGE_REGISTRY_USERNAME%" />
         <add key="ClearTextPassword" value="%GITLAB_PACKAGE_REGISTRY_PASSWORD%" />
     </gitlab>
 </packageSourceCredentials>
</configuration>

错误信息

$ export GITLAB_PACKAGE_REGISTRY_USERNAME="DeployUser" $ export
GITLAB_PACKAGE_REGISTRY_PASSWORD=$DeployPassword $ dotnet restore
${PROJECT} --packages ./.nuget/ --verbosity quiet
/usr/share/dotnet/sdk/5.0.408/NuGet.targets(565,5): error : Value
cannot be null or empty string. (Parameter 'password')
[/builds/codefactory/myproject.csproj]

问题原因

1. 分支匹配正则表达式错误

CI配置中only字段的正则写法存在两处错误:

  • 正则里的Production/包含斜杠/,而GitLab CI用/.../包裹正则表达式,斜杠会被识别为正则的分隔符,导致正则实际只解析为^Production,无法匹配Production/1.0这类带斜杠的分支名。
  • 版本号部分的.未转义,.在正则中代表任意字符,不能精准匹配版本号的点分隔符。

正确的正则表达式应为:/^Production\/[0-9]+(?:\.[0-9]+)+$/

2. CI变量未被正确注入

DeployPassword大概率是你设置的仅指定分支可用的受保护变量或分支限定变量。由于正则匹配错误,Production/1.0分支未被纳入only规则的允许范围内,导致该变量无法注入到CI环境中,$DeployPassword为空字符串。最终GITLAB_PACKAGE_REGISTRY_PASSWORD变量为空,nuget执行restore时因缺少有效密码抛出错误。

内容的提问来源于stack exchange,提问作者Carrie Kaski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:20:55