考虑下面的 Azure Devops Pipeline 模板:
parameters:
- name: projectName
type: string
- name: projectKey
type: string
- name: sonarHostUrl
type: string
- task: SonarQubePrepare@6
inputs:
SonarQube: 'SonarQubeOnDocker'
projectKey: ${{parameters.projectKey}}
projectName: ${{parameters.projectName}}
extraProperties: |
sonar.host.url=${{ parameters.sonarHostUrl }}
# Additional properties that will be passed to the scanner.
# Put one key=value per line, example:
# sonar.exclusions=**/*.bin
# sonar.verbose=true
# sonar.sources=src/
# sonar.tests=src/
# sonar.exclusions=/_/**/*
此模板用于准备 SonarQube 进行分析,是专用 Git 存储库的一部分,该存储库仅包含可重用的 YAML 模板;这些模板依次用于多个管道中。此特定模板不直接由任何管道使用,而是由另一个构建 .NET 解决方案的通用模板使用。因此,如果我想添加属性
sonar.exclusions
,我可以向 parameters
块添加另一个项目,但我必须向调用者添加相同的参数。如果我继续对所有其他 SonarQube 相关属性执行此操作,参数列表将变得非常大。
我想知道是否可以以编程方式填充
extraProperties
下的属性,而不是扩展此模板的参数数量(请注意,每个属性必须位于单独的行上)。如果可能的话,我想知道是否可以首先使用 Powershell 读取提取各种 SonarQube 相关属性的文件,然后将它们添加到 extraProperties
。
恐怕没有现成的方法可以读取文件中的属性并传递到单个管道中的sonarqube任务。
当我们读取文件中的属性时,我们需要使用日志命令(
echo "##vso[task.setvariable variable=xx;]xx"
)来设置Pipeline变量来传递值。但是,在使用日志记录命令设置变量时,Azure DevOps 不支持多行变量。所以这个方法无法在单管道中实现。
对于解决方法,我们可以使用两个管道来实现它。一个用于读取文件中的属性并触发另一个管道,另一个管道将使用对象类型参数来收集多行值并传递给sonarqube任务。
这是一个例子:
属性文件内容:
|\n sonar.exclusions=**/*.bin\n sonar.verbose=true\n sonar.tests=src/
管道一:
steps:
- powershell: |
$filecontent = Get-Content "properties.txt"
echo $filecontent
$token = "$(PAT)"
$url="https://dev.azure.com/{OrgName}/{ProjectNmae}/_apis/pipelines/{PipelineDefinitionID}/runs?api-version=5.1-preview"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = "
{
`"resources`": {
`"repositories`": {
`"self`": {
`"ref`": `"refs/heads/master`"
}
}
},
`"templateParameters`": {
`"InputProperties`":`"$($filecontent)`"
},
}"
$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json
管道二:
主要管道:
parameters:
- name: InputProperties
type: object
pool:
vmImage: ubuntu-latest
steps:
- template: template.yml
parameters:
Properties: ${{parameters.InputProperties}}
模板:
parameters:
- name: Properties
type: object
steps:
- task: SonarQubePrepare@6
inputs:
SonarQube: 'SonarQubeOnDocker'
organization: 'xx'
scannerMode: 'xx'
projectKey: 'xx'
projectName: 'xx
extraProperties: ${{parameters.Properties}}
此外,如果您想继续使用单个管道,则需要根据实际需求手动定义参数来设置 extraProperties 输入。