jenkins☞003共享库

阅读量: zyh 2021-01-16 20:07:13
Categories: > Tags:

基本

https://www.jenkins.io/zh/doc/book/pipeline/shared-libraries/

多个Jenkins工程的流水线可能包含重复代码,因此这些重复代码可以剥离出来从而被共享使用,这种东西叫共享库.

基本结构

(root)
+- src                     # Groovy source files
|   +- org
|       +- devops
|           +- tools.groovy  # for org.devops.tools class
+- vars
|   +- devops.groovy          # for global 'devops' variable
|   +- devops.txt             # help for 'devops' variable
+- resources               # resource files (external libraries only)
|   +- org
|       +- devops
|           +- tools.json    # static helper data for org.devops.Bar

基本写法

/src/org/devops/tools.groovy

package org.devops

//格式化输出, 需要AnsiColor插件支持.
def myPrint(content, color){
    colors = ['red'   : "\033[40;31m #############${content}############# \033[0m",
              'green' : "\033[40;32m #############${content}############# \033[0m",
              'yellow' : "\033[40;33m #############${content}############# \033[0m",
              'blue'  : "\033[47;34m #############${content}############# \033[0m"]
    ansiColor('xterm') {
        println(colors[color])
    }
}

//封装chatBot请求, 需要 http request 插件
def myChat(reqMode,reqUrl,reqBody){
    result = httpRequest httpMode: reqMode,
                accept: "APPLICATION_JSON_UTF8",
                contentType: "APPLICATION_JSON_UTF8",
                consoleLogResponseBody: true,
                ignoreSslErrors: true,
                requestBody: reqBody,
                url: reqUrl
                quiet: true
    return result
}

//根据标签获取目标机器ip, 并写入到 .hosts 文件中
//ipType: PublicIpAddress PrivateIpAddress
def getEc2Ip(ipType, tagKey, tagValue, Region) {
    sh """
      export AWS_DEFAULT_REGION=${Regionssss}
      aws ec2 describe-instances --filters "Name=tag:${tagKey},Values=${tagValue}" --query 'Reservations[*].Instances[*].[${ipType}]' --output text > .hosts
      cat .hosts
   """
}

def getRemoteIP(serverIP) {
    sh """
        echo ${serverIP} > .hosts
        cat .hosts
    """
}

// 获取阿里云 acr 服务的动态 token, 得到全局变量 ACRUSER 和 ACRPWD
// {"data":{"authorizationToken":"abcde123456","tempUserName":"cr_temp_user","expireDate":1612348203000}}
def getAliAcrToken(url) {
    sh (
        script: """curl -sq $url > acr.token;
            cat acr.token | jq -r .'["data"]["tempUserName"]' > acr.user;
            cat acr.token | jq -r .'["data"]["authorizationToken"]' >> acr.pwd;
        """
    )
}

// 需要提前部署好私钥 /root/.remote.pem
// 对应的公钥需要放置在目标机器的 ${remoteUser} 用户中
// .hosts 存放在工作目录下
def ansible(remoteUser,shellCommand) {
    sh """
        ansible -i .hosts --private-key /root/.remote.pem -u ${remoteUser} all -m shell -a "${shellCommand}"
    """
}

关联pipeline libraries

jenkins 系统管理-系统配置-Global Pipeline Libraries

这里将共享库放到git上,通过git拉去共享库.

image-20211102114354246

调用pipeline libraries

jenkins工程的pipeline代码开头添加,即jenkinsfile文件中

pipeline {
    @Library('jenkinslib') _  //导入lib库, 'jenkinslib' 名就是上一步里Global Pipeline Libraries配置的名
    def tools = new org.devops.tools()  //加载tools

    agent {
        ...
    }

    stages {
        stage("第一个阶段") {
            steps {
                tool.myPrint("第一个步骤","green")
            }
        }
    }

    post {
        ...
    }
}