在CentOS上编写Jenkins脚本时,遵循一些最佳实践和规范可以帮助你创建高效、可维护和可靠的自动化脚本。以下是一些关键的编写规范和示例。
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building..'
sh 'mvn clean install'
}
}
stage('Test') {
steps {
echo 'Testing..'
sh 'mvn test'
}
}
stage('Deploy') {
steps {
echo 'Deploying..'
sh 'scp target/*.jar user@remote:/deploy'
}
}
}
}
def buildApp() {
echo 'Building application...'
}
def runTests() {
echo 'Running unit tests...'
}
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
buildApp()
}
}
}
stage('Test') {
steps {
script {
runTests()
}
}
}
}
}
pipeline {
agent any
environment {
PROJECT_PATH '/home/jenkins/my_project'
VERSION 'v1.0'
}
stages {
stage('Checkout') {
steps {
echo "Cloning project from ${PROJECT_PATH}"
git url: "${PROJECT_PATH}"
}
}
stage('Build') {
steps {
echo "Building project version ${VERSION}"
sh 'mvn clean package -Dbuild.version=${VERSION}'
}
}
}
}
pipeline {
agent any
stages {
stage('Build') {
parallel {
stage('Build-Module1') {
steps {
sh 'mvn clean package -Dmodule=module1'
}
}
stage('Build-Module2') {
steps {
sh 'mvn clean package -Dmodule=module2'
}
}
}
}
}
}
pipeline {
agent any
stages {
stage('Example Stage with Exception Handling') {
steps {
script {
try {
// 尝试执行的代码块
echo "Trying to execute some code..."
// 这里可以调用其他函数或执行可能抛出异常的步骤
throw new Exception("Something went wrong!")
} catch (Exception e) {
// 捕获并处理异常
echo "Caught an exception: ${e.getMessage()}"
currentBuild.result = 'FAILURE'
throw e
}
}
}
}
}
}
通过遵循这些规范和示例,你可以编写出高效、可维护和可靠的Jenkins脚本,从而提升持续集成和持续交付的效率和质量。