我有一个代码块目前工作得很好。但是重用那个代码有点难看。
pipeline {
agent any
stages {
stage('Stage 1') {
steps {
script {
withCredentials([
gitUsernamePassword(credentialsId: 'jenkins-credentials', gitToolName: 'Default', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD')
]) {
sh '''#!/bin/bash
export GIT_USERNAME=${GIT_USERNAME};
export GIT_PASSWORD=${GIT_PASSWORD};
export PROYECT_DIRECTORY=${PROYECT_DIRECTORY};
export CHECKOUT_POINT=${CHECKOUT_POINT};
export GIT_HTTPS_REPO_DEPLOY=${GIT_HTTPS_REPO_DEPLOY};
export MARIADB_HOSTNAME=${MARIADB_HOSTNAME};
./scripts/awesome_script.sh
'''
}
}
}
}
}
}
问题是当我应用if语句在sh()块中使用diferents脚本bash时。脚本./scripts/awesome _script.sh
需要导出变量。因此代码看起来像这样。
script {
withCredentials([
gitUsernamePassword(credentialsId: 'jenkins-credentials', gitToolName: 'Default', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD')
]) {
sh '''#!/bin/bash
export GIT_USERNAME=${GIT_USERNAME};
export GIT_PASSWORD=${GIT_PASSWORD};
export PROYECT_DIRECTORY=${PROYECT_DIRECTORY};
export CHECKOUT_POINT=${CHECKOUT_POINT};
export GIT_HTTPS_REPO_DEPLOY=${GIT_HTTPS_REPO_DEPLOY};
export MARIADB_HOSTNAME=${MARIADB_HOSTNAME};
./scripts/awesome_script.sh
'''
if(env.APP_ENV == 'testing'){
sh '''#!/bin/bash
export GIT_USERNAME=${GIT_USERNAME};
export GIT_PASSWORD=${GIT_PASSWORD};
export PROYECT_DIRECTORY=${PROYECT_DIRECTORY};
export CHECKOUT_POINT=${CHECKOUT_POINT};
export GIT_HTTPS_REPO_DEPLOY=${GIT_HTTPS_REPO_DEPLOY};
export MARIADB_HOSTNAME=${MARIADB_HOSTNAME};
./scripts/awesome_script_2.sh
'''
}
}
}
很丑,对吧?
我正在查找的内容与以下内容类似,但语法正确:
script {
env.STRING_BLOCK_WITHOUT_PROCESSING = '''
export GIT_USERNAME=${GIT_USERNAME};
export GIT_PASSWORD=${GIT_PASSWORD};
export PROYECT_DIRECTORY=${PROYECT_DIRECTORY};
export CHECKOUT_POINT=${CHECKOUT_POINT};
export GIT_HTTPS_REPO_DEPLOY=${GIT_HTTPS_REPO_DEPLOY};
export MARIADB_HOSTNAME=${MARIADB_HOSTNAME};
''';
withCredentials([
gitUsernamePassword(credentialsId: 'jenkins-credentials', gitToolName: 'Default', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD')
]) {
sh '''#!/bin/bash
${STRING_BLOCK_WITHOUT_PROCESSING}
./scripts/awesome_script.sh
'''
if(env.APP_ENV == 'testing'){
sh '''#!/bin/bash
${STRING_BLOCK_WITHOUT_PROCESSING}
./scripts/awesome_script_2.sh
'''
}
}
}
谢谢你能给予我的所有帮助。〈3
1条答案
按热度按时间b4lqfgs41#
如果你想的话,你可以用
withCredentials
块来 PackagewithEnv
块。