• Jenkins pipline集成发布到K8s


     流程结构

     

    一、创建一个新的Jenkins项目

    二、增加参数化配置

    这里定义两个参数: 

    git_url: 从gitlab拉取代码用

    current_date: 当前时间,构建docker镜像时使用

    三、使用脚本方式配置pipeline

     

     四、pipeline脚本说明

    pipeline语法很容易,这里不多说

    pipeline步骤如下: 拉取代码-->maven构建成可执行的jar-->docker打包成镜像并推送到镜像仓库Harbor --> 从Harbor拉取镜像部署到k8s。 

    这里用到的几个认证,都需要事先配置好,

    1、gitlab: 使用用户名和密码认证:credentialsId:'xxxxx'

    2、Harbor: 这里我使用的在jenkins所在服务器上执行docker login xx.xx.xx.xx成功即可,login时会需要输入用户名和密码。

    这里打包时生成了以当前日期(current_date)和编译号(BUILD_NUMBER)为版本号的镜像,同时更新当前镜像为latest。方便部署的时候直接引用最新镜像。

    3、K8s部署,

    网上查找资料大多安装插件,但不同jenkins所对应的插件有不兼容的情况,因此这里直接使用配置文件的方式 

    在这里增加一个配置文件,这是我增加的kubeconfig的配置文件。

    点击Add a new config增加一条配置

    自定义ID和Name, 文件内容写k8s集群中的~/.kube/config的内容,我这里对server做了一修改,目的是为了jenkins所在服务器能够连通K8s集群。点击"submit“保存即可。

     在pipeline脚本中如是写:

     deployment.yml里面的内容大家可以根据自身需要进行修改。

     五、完整的脚本如下

     

    1. pipeline {
    2. agent any
    3. tools {
    4. maven 'maven363'
    5. }
    6. stages {
    7. stage('拉取代码') {
    8. steps {
    9. echo "拉取分支= master"
    10. checkout([$class: 'GitSCM', branches: [[name: "master"]],
    11. doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [],
    12. userRemoteConfigs: [[credentialsId: 'xxxxxxxx', url:"${git_url}"]]])
    13. }
    14. }
    15. stage('构建'){
    16. steps{
    17. sh '''
    18. mvn install -f sample/sample-boot/sampleBoot/pom.xml -Dmaven.test.skip=true -U
    19. '''
    20. }
    21. }
    22. stage('构建推送镜像'){
    23. steps{
    24. sh '''
    25. mkdir -p /data/cicd/sample/app/target
    26. mv sample/sample-boot/sampleBoot/target/sample-boot-1.0-SNAPSHOT.jar /data/cicd/sample/app/target/app.jar
    27. docker build -t sample-boot:${current_date}-${BUILD_NUMBER} /data/cicd/sample/app
    28. docker tag sample-boot:${current_date}-${BUILD_NUMBER} xx.xx.xx.xx/xxx/sample-boot:${current_date}-${BUILD_NUMBER}
    29. docker tag sample-boot:${current_date}-${BUILD_NUMBER} xx.xx.xx.xx/xxx/sample-boot:latest
    30. docker push xx.xx.xx.xx/xxx/sample-boot:${current_date}-${BUILD_NUMBER}
    31. docker push xx.xx.xx.xx/xxx/sample-boot:latest
    32. '''
    33. }
    34. }
    35. stage('部署K8s'){
    36. steps{
    37. configFileProvider([configFile(fileId: "k8sconfig", targetLocation: 'kubeconfig')]) {
    38. sh """
    39. kubectl apply -f /data/cicd/sample/app/k8s/deployment.yml --kubeconfig=kubeconfig
    40. """
    41. }
    42. }
    43. }
    44. }
    45. }

     根据deployment.yml里的namespace,事先在k8s里面建立好。

    kubectl create ns sample

  • 相关阅读:
    学过单片机的都知道,节电器到底能不能省电
    B - 缺失的数据范围
    竞赛 深度学习交通车辆流量分析 - 目标检测与跟踪 - python opencv
    SpringBoot程序具有哪些优点呢?
    6.1、Flink数据写入到文件
    牛客多校九 - Here is an Easy Problem of Zero-chan (树形DP,推公式,贡献)
    socket选项
    java集合总结
    URP渲染管线场景优化实战 1.1 预配置及初始信息
    python中的闭包函数&装饰器
  • 原文地址:https://blog.csdn.net/spider_zhcl/article/details/127803933