OpenShift - 构建自动化

在 OpenShift 中,我们有多种自动化构建管道的方法。为了做到这一点,我们需要创建一个 BuildConfig 资源来描述构建流程。BuildConfig 中的流程可以与 Jenkins 作业定义中的作业定义进行比较。在创建构建流程时,我们必须选择构建策略。

BuildConfig 文件

在 OpenShift 中,BuildConfig 是一个用于连接到 API 然后创建新实例的 rest 对象。

kind: "BuildConfig"
apiVersion: "v1"
metadata:
   name: "<Name of build config file>"
spec:
   runPolicy: "Serial"
   triggers:
   -
      type: "GitHub"
      github:
         secret: "<Secrete file name>"
   - type: "Generic"
   generic:
      secret: "secret101"
   -
   type: "ImageChange"
   source:
      type: "<Source of code>"
      git:
   uri: "https://github.com/openshift/openshift-hello-world"
   dockerfile: "FROM openshift/openshift-22-centos7
USER example"
   strategy:
      type: "Source"
      
sourceStrategy:
   from:
      kind: "ImageStreamTag"
      name: "openshift-20-centos7:latest"
   output:
      to:
         kind: "ImageStreamTag"
         name: "origin-openshift-sample:latest"
   postCommit:
      script: "bundle exec rake test"

在 OpenShift 中,有四种类型的构建策略。

  • 源到镜像策略
  • Docker 策略
  • 自定义策略
  • 管道策略

源到镜像策略

允许从源代码开始创建容器镜像。在此流程中,实际代码首先在容器中下载,然后在容器内进行编译。编译后的代码将部署在同一容器内,并根据该代码构建镜像。

strategy:
   type: "Source"
   sourceStrategy:
      from:
         kind: "ImageStreamTag"
         name: "builder-image:latest"
      forcePull: true

有多种策略策略。

  • Forcepull
  • 增量构建
  • 外部构建

Docker 策略

在此流程中,OpenShift 使用 Dockerfile 构建映像,然后将创建的映像上传到 Docker 注册表。

strategy:
   type: Docker
   dockerStrategy:
      from:
         kind: "ImageStreamTag"
         name: "ubuntu:latest"

Docker 文件选项可以在多个位置使用,从文件路径、无缓存和强制拉取开始。

  • 从图像
  • Dockerfile 路径
  • 无缓存
  • 强制拉取

自定义策略

这是不同类型的构建策略之一,其中没有强制要求构建的输出是图像。它可以与 Jenkins 的自由式作业进行比较。通过它,我们可以创建 Jar、rpm 和其他包。

strategy:
   type: "Custom"
   customStrategy:
      from:
         kind: "DockerImage"
         name: "openshift/sti-image-builder"

它由多种构建策略组成。

  • 公开 Docker 套接字
  • 机密
  • 强制拉取

管道策略

管道策略用于创建自定义构建管道。这基本上用于在管道中实现工作流。此构建流程使用 Groovy DSL 语言的自定义构建管道流程。OpenShift 将在 Jenkins 中创建一个管道作业并执行它。此管道流程也可以在 Jenkins 中使用。在此策略中,我们使用 Jenkinsfile 并将其附加到 buildconfig 定义中。

Strategy:
   type: "JenkinsPipeline"
   jenkinsPipelineStrategy:
   jenkinsfile: "node('agent') {
stage 'build'
openshiftBuild(buildConfig: 'OpenShift-build', showBuildLogs: 'true')
stage 'deploy'
openshiftDeploy(deploymentConfig: 'backend')
}"

使用构建管道

kind: "BuildConfig"
apiVersion: "v1"
metadata:
   name: "test-pipeline"
spec:
   source:
      type: "Git"
      git:
         uri: "https://github.com/openshift/openshift-hello-world"
   strategy:
      type: "JenkinsPipeline"
      jenkinsPipelineStrategy:
         jenkinsfilePath: <file path repository>