Jenkinsfile参数中的访问变量

时间:2019-02-27 14:55:32

标签: jenkins jenkins-pipeline

我正在尝试在Jenkinsfile中创建参数,默认为BUILD_NUMBER

pipeline {
    agent { label 'windows' }

    options {
        copyArtifactPermission("${JOB_NAME}");
    }

    parameters {
        string(
            name: 'DEPLOY_BUILD_NUMBER',
            defaultValue: "${env.BUILD_NUMBER}",
            description: 'Fresh Build and Deploy OR Deploy Previous Build Number'
        )
    }

    stages {
        stage ('Build') {
            steps {
                sh '''
                   echo "Building Project"
                   Echo "Packaging into tar.gz"
                '''
            }
            post {
                success {
                    archiveArtifacts artifacts: '*.tar.gz'
                }
            }
        }
        stage ('Deploy') {
            steps {
                echo "Deploying...."
                echo "${params.DEPLOY_BUILD_NUMBER}"
                echo "${env.BUILD_NUMBER}"
                script {
                    step ([$class: 'CopyArtifact',
                         projectName: '${JOB_NAME}',
                         filter: "*.tar.gz",
                         fingerprintArtifacts: true,
                         selector: [$class: 'SpecificBuildSelector', buildNumber: "${params.DEPLOY_BUILD_NUMBER}"]
                         ]);
                }
            }
        }
    }
    post {
        success {
            script {
                currentBuild.displayName = "#${BUILD_NUMBER}"
            }
        }
    }
}

但这实际上不是在打印内部版本

[Pipeline] echo
Deploying....
[Pipeline] echo
env.BUILD_NUMBER
[Pipeline] echo
144

我引用env.BUILD_NUMBER时需要更改以获得实际的params.DEPLOY_BUILD_NUMBER值。

1 个答案:

答案 0 :(得分:2)

您可以通过在参数中将内部版本号称为env.BUILD_NUMBER来解决此问题。给定您的示例代码,它看起来像:

parameters {
  string(
    name: 'DEPLOY_BUILD_NUMBER',
    defaultValue: "${env.BUILD_NUMBER}",
    description: 'Fresh Build and Deploy OR Deploy Previous Build Number'
  )
}

请注意,env.BUILD_NUMBER被强制转换为字符串(无论如何您都想要),但是例如,如果您需要对其进行算术运算,则需要执行以下操作:

parameters {
  string(
    name: 'DEPLOY_BUILD_NUMBER',
    defaultValue: "${env.BUILD_NUMBER.toInteger() + 1}",
    description: 'Fresh Build and Deploy OR Deploy Previous Build Number'
  )
}

这会将env.BUILD_NUMBER重铸为整数,并向其中添加一个,然后参数中的string()规范会将其强制转换回字符串。

现在要实际使用DEPLOY_BUILD_NUMBER参数,您需要从params映射中引用它,例如params.DEPLOY_BUILD_NUMBER

steps {
  echo "${params.DEPLOY_BUILD_NUMBER}"
  script {
    step ([$class: 'CopyArtifact',
      projectName: '${JOB_NAME}',
      filter: "*.tar.gz",
      fingerprintArtifacts: true,
      selector: [$class: 'SpecificBuildSelector', buildNumber: "${params.DEPLOY_BUILD_NUMBER}"]
    ]);
  }
}