Jenkins 自动化脚本编写一般分三种常见场景,不同场景写法差别很大。下面我按从常见到高级的方式给你说明,并给出可直接用的示例,你可以按需取用。
pipeline {
agent any
environment {
APP_NAME = "my-app"
VERSION = "1.0.0"
}
stages {
stage('拉取代码') {
steps {
git branch: 'main',
url: 'https://github.com/your/repo.git'
}
}
stage('构建') {
steps {
sh 'npm install'
sh 'npm run build'
}
}
stage('测试') {
steps {
sh 'npm test'
}
}
stage('部署') {
steps {
sh 'scp -r dist/* user@server:/var/www/html/'
}
}
}
post {
success {
echo '✅ 构建成功'
}
failure {
echo '❌ 构建失败'
}
}
}
node {
stage('拉取代码') {
git 'https://github.com/your/repo.git'
}
stage('构建') {
sh 'mvn clean package'
}
stage('部署') {
sh 'java -jar target/app.jar &'
}
}
pipeline {
agent any
parameters {
choice(name: 'ENV', choices: ['dev', 'test', 'prod'], description: '部署环境')
booleanParam(name: 'RUN_TEST', defaultValue: true, description: '是否执行测试')
}
stages {
stage('部署') {
steps {
echo "部署到 ${ENV} 环境"
sh "./deploy.sh ${ENV}"
}
}
}
}
pipeline {
agent any
environment {
GIT_CRED = credentials('git-credential-id')
}
stages {
stage('Clone') {
steps {
git url: 'https://github.com/your/repo.git',
credentialsId: 'git-credential-id'
}
}
}
}
deploy.sh#!/bin/bash
ENV=$1
if [ -z "$ENV" ]; then
echo "请指定环境:dev/test/prod"
exit 1
fi
echo "开始部署到 $ENV 环境"
scp target/app.jar user@server:/app/${ENV}/
echo "部署完成"
pipeline {
triggers {
cron('H 2 * * *') // 每天凌晨2点
}
}
curl -X POST http://jenkins_url/job/JOB_NAME/build \
--user user:API_TOKEN
curl -X POST \
"http://jenkins_url/job/JOB_NAME/buildWithParameters?ENV=prod"
| 场景 | 推荐脚本 |
|---|---|
| CI/CD 流水线 | Jenkinsfile |
| 定时任务 | triggers + cron |
| 多环境部署 | parameters |
| 远程构建 | API + curl |
| 服务器部署 | SSH / Shell |
你可以直接告诉我:
我可以直接帮你 写一份完整可用的 Jenkins 自动化脚本。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。