温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Jenkins自动化服务器脚本编写

发布时间:2026-06-30 14:50:02 来源:亿速云 阅读:84 作者:小樊 栏目:系统运维

Jenkins 自动化脚本编写一般分三种常见场景,不同场景写法差别很大。下面我按从常见到高级的方式给你说明,并给出可直接用的示例,你可以按需取用。


一、Jenkinsfile(Pipeline 脚本,最常用 ✅)

1️⃣ 声明式 Pipeline(推荐)

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 '❌ 构建失败'
        }
    }
}

2️⃣ 脚本式 Pipeline(更灵活)

node {
    stage('拉取代码') {
        git 'https://github.com/your/repo.git'
    }

    stage('构建') {
        sh 'mvn clean package'
    }

    stage('部署') {
        sh 'java -jar target/app.jar &'
    }
}

二、Jenkins 参数化构建脚本(常用)

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}"
            }
        }
    }
}

三、使用凭据(Credentials)示例

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'
            }
        }
    }
}

四、Jenkins + Shell 自动化脚本(通用)

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 "部署完成"

五、定时构建(Cron 表达式)

pipeline {
    triggers {
        cron('H 2 * * *')   // 每天凌晨2点
    }
}

六、远程触发 Jenkins Job(脚本触发)

1️⃣ curl 触发

curl -X POST http://jenkins_url/job/JOB_NAME/build \
--user user:API_TOKEN

2️⃣ 带参数触发

curl -X POST \
"http://jenkins_url/job/JOB_NAME/buildWithParameters?ENV=prod"

七、常见自动化场景总结

场景 推荐脚本
CI/CD 流水线 Jenkinsfile
定时任务 triggers + cron
多环境部署 parameters
远程构建 API + curl
服务器部署 SSH / Shell

八、我可以继续帮你的方向 ✅

你可以直接告诉我:

  1. 语言(Java / Node / Python / Docker)
  2. 部署方式(服务器 / K8s / Docker)
  3. 是否用 GitLab / GitHub
  4. Jenkins 是单机还是分布式

我可以直接帮你 写一份完整可用的 Jenkins 自动化脚本

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI