多分支流水线
gitlab管理的UI项目下细分为2个模块admin、mobile,每个模块为1个目录。gitlab的触发只能针对UI整个项目,为了让子模块admin的改动不触发mobile的构建,在commits中获取模块名字,然后让正则表达式去匹配。
pipeline {
agent any
//禁止并行构建
options {
disableConcurrentBuilds()
}
//自动触发构建,并按不同模块触发
triggers {
GenericTrigger(
genericVariables: [
[key: 'ref', value: '$.ref'],
[key: 'commits', value: '$.commits[*].[\'modified\',\'added\',\'removed\'][*]'] //获取commits中的变更内容
],
causeString: 'Triggered on $ref',
token: 'UI', //不同项目填写不同token,让gitlab知道触发哪个项目
printContributedVariables: true,
printPostContent: true,
regexpFilterText: '$ref $commits',
regexpFilterExpression: 'refs/heads/'+env.BRANCH_NAME+' '+'.*admin.*' //如果commits中包含admin,则触发
)
}
stages {
stage('env') {
steps {
sh 'printenv' //打印构建过程中的变量
}
}
stage('deploy to dev') {
when {
branch 'dev*'
}
steps {
echo 'dev'
}
}
stage('deploy to staging') {
when {
branch 'staging*'
}
steps {
echo 'staging'
}
}
stage('deploy to prd') {
when {
branch 'master'
}
steps {
echo 'master'
}
}
}
}
SSH命令
基于密钥登陆
def getRemoteHost(ip,user){
def remote = [:]
remote.name = ip
remote.host = ip
remote.user = user
remote.identityFile = identity
remote.port = 22
remote.allowAnyHosts = true
return remote
}
pipeline {
agent any
environment {
//远程服务器信息
ssh_ip = 'x.x.x.x'
ssh_user= "root"
ssh_key_uid = "server_privatekey" //Jenkins “凭据”-“系统”-”全局凭据“ 中添加”Secret text“,ID为server_privatekey
}
stages {
stage('远程服务器操作'){
steps {
//SSH操作服务器
withCredentials([sshUserPrivateKey(credentialsId: "${ssh_key_uid}", keyFileVariable: 'identity')]){
sshCommand remote: getRemoteHost(ssh_ip,ssh_user), command: "echo" //在远程服务器执行echo命令
sshPut remote: getRemoteHost(ssh_ip,ssh_user), from: "/tmp/1.txt", into: "/tmp" //将本地/tmp/1.txt传送到远程服务器的/tmp目录下
}
}
}
}
}
基于用户名密码登陆
def getRemoteHost(ip,user,password){
def remote = [:]
remote.name = ip
remote.host = ip
remote.user = user
remote.password = password
remote.port = 22
remote.allowAnyHosts = true
return remote
}
pipeline {
agent any
environment {
//远程服务器信息
ssh_name = 'x.x.x.x'
// 目标服务器信息
ssh_ip = 'x.x.x.x'
ssh_port = 22
SSH_CREDS = credentials('serverXXX')
ssh_user= "${SSH_CREDS_USR}"
ssh_password = "${SSH_CREDS_PSW}" //Jenkins “凭据”-“系统”-”全局凭据“ 中添加”Username with password“,ID为serverXXX
}
stages {
stage('远程服务器操作'){
steps {
//SSH操作服务器
sshCommand remote: getRemoteHost(ssh_ip,ssh_user,ssh_password), command: "echo" //在远程服务器执行echo命令
sshPut remote: getRemoteHost(ssh_ip,ssh_user,ssh_password), from: "/tmp/1.txt", into: "/tmp" //将本地/tmp/1.txt传送到远程服务器的/tmp目录下
}
}
}
}