jenkins-示例1

阅读量: zyh 2020-04-23 11:12:11
Categories: > Tags:

简介

本例子是传统例子,执行步骤如下:

  1. 拉取代码
  2. 根据代码的Dockerfile,打包 docker 镜像,并清理24小时之前的镜像
  3. 推送镜像到代码仓库
  4. 获取更新服务所在的服务器的ip,并写入到jenkins工作目录的.hosts文件中。ansible从.hosts中获取远程服务器ip
  5. 在jenkins工作目录中,调用ansible在远程服务器中执行用户传递的shell命令
  6. 如果成功,就推送jenkins工程信息到企业微信

Jenkinslib

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])
    }
}

//封装wechatBot请求, 需要 http request 插件
def myHttp(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
}

//根据aws ec2服务器上用户设定的一对一的特定标签对,获取服务器的公有ip或者私有ip, 并写入到 .hosts 文件中
//ipType: PublicIpAddress PrivateIpAddress
//需要jenkins工作节点拥有 aws ec2 describe-instances 权限
def getEc2Ip(ipType, tagKey, tagValue, Region) {
   sh """
      export AWS_DEFAULT_REGION=${Region}
      aws ec2 describe-instances --filters "Name=tag:${tagKey},Values=${tagValue}" --query 'Reservations[*].Instances[*].[${ipType}]' --output text > .hosts
      cat .hosts
   """ 
}

//ansible 远程执行 shellCommand 传递的 shell 命令
//需要提前在jenkins工作节点上部署好私钥,对应的公钥需要放置在 .hosts 文件中记录的服务器用户 ec2-user 下的 .ssh/authorized_keys 文件中
def ansible(remoteUser,shellCommand) {
    sh """
        ansible -i .hosts --private-key /var/jenkins_home/.ec2-user.pem -u ${remoteUser} -b --become-user root all -m shell -a "${shellCommand}"
    """
}

Jenkinsfile

#!groovy
// 需要先编写共享库和配置共享库, 这里配置的共享库名叫 jenkinslib.
@Library('jenkinslib') _
def mytools = new org.devops.mytools()
def JOB_MY_RESULT="""
       - 项目:${JOB_NAME}
       - 编号:${BUILD_ID}
    """

pipeline {
    agent any
    parameters {
        // git pull
        string(defaultValue: 'http://git.xxx.com/demo/test.git', description: 'git url', name: 'gitUrl')
        string(defaultValue: 'master', description: 'git branch', name: 'branchVersion')
        string(defaultValue: 'jenkins-pull-token', description: 'jenkins git credentialsId', name: 'gitCredId')
        
        // docker build and docker push and docker pull and docker run
        string(defaultValue: 'xxx.dkr.ecr.us-east-1.amazonaws.com', description: 'build docker image domain', name: 'dockerImageDomain')
        string(defaultValue: 'it/busybox:latest', description: 'build docker image version', name: 'dockerImageTag')
        
        // get ec2 ip
        choice(choices: 'PublicIpAddress\nPrivateIpAddress', description: 'get aws ec2 wan_ip or lan_ip', name: 'ipType')
        string(defaultValue: 'dockerImageName', description: 'tag key of the app', name: 'tagKey')
        string(defaultValue: 'boggle/boggle_server', description: 'tag value of the app', name: 'tagValue')
        string(defaultValue: 'us-east-1', description: 'region where app is running', name: 'Region')
        
        // ansible 
        string(defaultValue: 'ec2-user', description: 'ansible remote user', name: 'ansibleRemoteUser')
        string(defaultValue: "docker pull xxx.dkr.ecr.us-east-1.amazonaws.com/it/busybox:latest;docker rm -f busybox;docker run --name busybox xxx.dkr.ecr.us-east-1.amazonaws.com/it/busybox:latest", description: 'ansible shell module args', name: 'ansibleShellCommand')
        
        //set wechatbot
        string(defaultValue: 'POST', description: 'http request method(GET,POST)', name: 'reqMode')
        string(defaultValue: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<chatbotid>', description: 'http request url', name: 'reqUrl')
    }
    tools {
        git "git"
    }
    stages {
        stage('Clone Code') {
            steps {
                git branch: params.branchVersion, changelog: false, credentialsId: params.gitCredId, poll: false, url: params.gitUrl
                sh "rm -rf boggle_common && cp -rp ../boggle_common ./"
            }
        }
        stage('Build Docker Image') {
            steps {
                sh """
                    whoami
                    docker image list
                    docker build . -t ${dockerImageDomain}/${dockerImageTag}
                    docker image prune -a -f --filter "until=24h"
                """
            }
        }
        stage('Push Docker Image To AWS ECR') {
            steps {
                sh """
                    aws ecr get-login-password --region ${Region} | docker login --username AWS --password-stdin ${dockerImageDomain}
                    docker push ${dockerImageDomain}/${dockerImageTag}
                """
            }
        }
        stage('Make Ansible Hosts') {
            steps {
                script{
                    mytools.getEc2Ip(ipType, tagKey, tagValue, Region)
                }
            }
        }
        stage('Start Latest Tag Container On Remote Machine') {
            steps {
                script{
                    mytools.ansible(ansibleRemoteUser,"aws ecr get-login-password --region ${Region} | docker login --username AWS --password-stdin ${dockerImageDomain};${ansibleShellCommand}")
                }
            }
        }
    }
    post{
        success{
            script{
                mytools.myPrint(JOB_MY_RESULT, 'green')
                // 构建http post请求, 需要安装HTTP Request Plugin
                wechatData="""{"msgtype":"markdown","markdown":{"content": "${JOB_MY_RESULT}"}}"""
                wechatResult = mytools.myHttp(params.reqMode, params.reqUrl, wechatData)
            }
        }
        failure{ script{ mytools.myPrint(JOB_MY_RESULT, 'red') }}
        aborted{ script{ mytools.myPrint(JOB_MY_RESULT, 'yellow') }}
        unstable{ script{ mytools.myPrint(JOB_MY_RESULT, 'yellow') }}
        changed{ script{ mytools.myPrint(JOB_MY_RESULT, 'yellow') }}
    }
}