Azure DevOps YAML流水线动态设置dotnet发布AssemblyVersion失败求助
Azure DevOps YAML流水线AssemblyVersion变量未解析问题排查与解决
问题场景
已知可通过命令行参数直接设置dotnet构建的AssemblyVersion,示例命令:
dotnet publish -f net8.0-ios -c Release -p:AssemblyVersion=2024.01.25.5 -p:BuildIpa=True -o ./artifacts
为在Azure DevOps YAML流水线中动态生成AssemblyVersion,定义如下变量:
variables: DotNetVersion: '8.x' AssemblyVersion: $(Date:yyyy).$(Date:MM).$(Date:dd)$(Rev:.r)
并在Bash任务中引用该变量:
- task: Bash@3 displayName: Build iOS App inputs: targetType: 'inline' script: | cd src dotnet publish -f net8.0-ios -c Release -p:AssemblyVersion=$ASSEMBLYVERSION -p:BuildIpa=True -o ./artifacts
执行后报错,变量未被解析,直接以原字符串传入:
error CS7034: The specified version string '$(Date:yyyy).$(Date:MM).$(Date:dd)$(Rev:.r)' does not conform to the required format
尝试${{variables.AssemblyVersion}}和$[[variables.AssemblyVersion]]后问题仍存在。
问题原因
$(Date:yyyy)和$(Rev:.r)是Azure DevOps经典流水线专属的内置变量语法,YAML流水线不支持直接解析这类语法。将其写入YAML变量时,会被当作普通字符串处理,无法自动生成对应的日期和递增版本号。
同时:
${{ variables.AssemblyVersion }}是编译时替换,此时变量内的$(Date:)等未被识别的语法会原样保留;$[[variables.AssemblyVersion]]是运行时表达式,但YAML流水线没有内置解析$(Date:)的逻辑,因此也无法生成预期的版本号。
解决方法
方法1:使用YAML流水线原生表达式生成版本号
利用YAML的format和counter表达式,结合流水线内置的pipeline.startTime变量生成日期+递增序号的版本号:
variables: DotNetVersion: '8.x' # 生成格式:yyyy.MM.dd.当日递增序号(从1开始) AssemblyVersion: $[format('{0:yyyy}.{0:MM}.{0:dd}.{1}', pipeline.startTime, counter(format('{0:yyyyMMdd}', pipeline.startTime), 1))]
然后在Bash任务中使用编译时变量引用:
- task: Bash@3 displayName: Build iOS App inputs: targetType: 'inline' script: | cd src dotnet publish -f net8.0-ios -c Release -p:AssemblyVersion=${{ variables.AssemblyVersion }} -p:BuildIpa=True -o ./artifacts
方法2:通过脚本生成并设置变量
添加前置Bash任务,用shell命令生成版本号,再通过Azure DevOps任务命令将其设置为流水线变量:
- task: Bash@3 displayName: Generate AssemblyVersion inputs: targetType: 'inline' script: | # 生成日期部分:YYYY.MM.DD DATE_PART=$(date +%Y.%m.%d) # 生成递增部分:用BuildId取模或自定义计数器 REV_PART=$(($(Build.BuildId) % 1000)) # 组合版本号 ASSEMBLY_VERSION="$DATE_PART.$REV_PART" # 设置为流水线变量,后续任务可直接引用 echo "##vso[task.setvariable variable=AssemblyVersion;]$ASSEMBLY_VERSION" - task: Bash@3 displayName: Build iOS App inputs: targetType: 'inline' script: | cd src dotnet publish -f net8.0-ios -c Release -p:AssemblyVersion=$ASSEMBLYVERSION -p:BuildIpa=True -o ./artifacts
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

