olu*_*nt6 5 powershell command-line jenkins jenkins-pipeline
在Jenkins Pipeline中使用PowerShell时,是否有人遇到问题?当您尝试引入环境变量(例如$env:CHANGE_ID)时,它会得出类似的结果?
org.jenkinsci.plugins.workflow.cps.EnvActionImpl@1b69f5bb:VARIABLE_NAME
Run Code Online (Sandbox Code Playgroud)
看来其他人在这个问题上遇到了相同的问题,但是我不确定在那里是否得到了答案(他们展示了如何打印所有环境变量,但是没有展示如何在toString未实现时获取特定的环境变量):
在Jenkinsfile中检索env的所有属性
我的Jenkins管道文件:
pipeline {
agent {
node {
label 'jenkins_managed_windows'
}
}
stages {
stage('SonarQube Analysis') {
steps {
powershell "dotnet sonarscanner begin /k:project-key /d:sonar.branch.name=$env:BRANCH_NAME"
}
}
stage('Build') {
steps {
powershell 'dotnet build'
}
}
stage('SonarQube End') {
steps {
powershell 'dotnet sonarscanner end'
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
包含环境变量的步骤运行为:
dotnet sonarscanner begin /k:project-key /d:sonar.branch.name=org.jenkinsci.plugins.workflow.cps.EnvActionImpl@54ee3a8:BRANCH_NAME
Run Code Online (Sandbox Code Playgroud)
powershell 'dotnet sonarscanner begin /k:project-key /d:sonar.branch.name=$env:BRANCH_NAME'
Run Code Online (Sandbox Code Playgroud)
它甚至根本不评估环境变量,而只是运行为:
dotnet sonarscanner begin /k:project-key /d:sonar.branch.name=$env:BRANCH_NAME
Run Code Online (Sandbox Code Playgroud)
语法形式$env:BRANCH_NAME和等效项${env:BRANCH_NAME}是PowerShell构造,这意味着为了将它们通过内插Groovy字符串 ( )传递给 PowerShell ,您必须对字符进行转义以防止Groovy预先解释该构造:"..."\$
powershell "dotnet sonarscanner begin ... /d:sonar.branch.name=\$env:BRANCH_NAME"
Run Code Online (Sandbox Code Playgroud)
也就是说,假设您的命令不包含需要插值的Groovy变量(让PowerShell引用环境变量更安全且更可靠),您可以简单地使用字面Groovy 字符串 ,'...'其中$chars. 发往 PowerShell不需要转义:
powershell 'dotnet sonarscanner begin ... /d:sonar.branch.name=$env:BRANCH_NAME'
Run Code Online (Sandbox Code Playgroud)
至于你尝试过的:
"... $env:BRANCH_NAME"插入 Groovy 字符串会导致 Groovy 插入变量env(因为它前面带有$),并视为:BRANCH_NAME文字。
由于env引用包含所有环境变量的对象,因此您看到的是该对象的(无用的)字符串化,即类名 ( org.jenkinsci.plugins.workflow.cps.EnvActionImpl) 后跟特定于实例的哈希码 ( @54ee3a8)。
使用${env.BRANCH_NAME}该方法是可行的——假设环境变量的值BRANCH_NAME可以作为对象的属性来访问env——但请注意,这意味着Groovy预先插入该值,然后 PowerShell 只能看到结果值。
在简单的情况下(没有空格或特殊字符的环境变量值),"${env.BRANCH_NAME}"(Groovy 的预先插值)和"\${env:BRANCH_NAME}"(PowerShell 的后续解释)是可以互换的,但只有后一种方法对所有值都可以稳健地工作。
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |