7.4. Jenkinsfile을 사용하여 파이프라인 생성

이 섹션에서는 3scale 툴박스를 사용하는 Groovy에서 처음부터 사용자 지정 Jenkinsfile 을 작성하는 모범 사례를 제공합니다.

중요

Red Hat은 Red Hat 통합 리포지토리에 제공된 Jenkins 파이프라인 샘플을 지원합니다.

이러한 파이프라인에 대한 수정 사항은 Red Hat에서 직접 지원하지 않습니다. 환경에 대해 생성한 사용자 지정 파이프라인은 지원되지 않습니다. 이 섹션은 참조용으로만 제공됩니다.

사전 요구 사항

절차

  1. 3scale toolbox를 호출하는 유틸리티 함수를 작성합니다. 다음은 3scale toolbox를 실행하는 Kubernetes 작업을 생성합니다.

    #!groovy
    
    def runToolbox(args) {
      def kubernetesJob = [
        "apiVersion": "batch/v1",
        "kind": "Job",
        "metadata": [
          "name": "toolbox"
        ],
        "spec": [
          "backoffLimit": 0,
          "activeDeadlineSeconds": 300,
          "template": [
            "spec": [
              "restartPolicy": "Never",
              "containers": [
                [
                 "name": "job",
                 "image": "registry.redhat.io/3scale-amp2/toolbox-rhel7:3scale2.11",
                 "imagePullPolicy": "Always",
                 "args": [ "3scale", "version" ],
                 "env": [
                   [ "name": "HOME", "value": "/config" ]
                 ],
                 "volumeMounts": [
                   [ "mountPath": "/config", "name": "toolbox-config" ],
                   [ "mountPath": "/artifacts", "name": "artifacts" ]
                  ]
                ]
              ],
              "volumes": [
                [ "name": "toolbox-config", "secret": [ "secretName": "3scale-toolbox" ] ],
                [ "name": "artifacts", "configMap": [ "name": "openapi" ] ]
              ]
            ]
          ]
        ]
      ]
    
      kubernetesJob.spec.template.spec.containers[0].args = args
    
      sh "rm -f -- job.yaml"
      writeYaml file: "job.yaml", data: kubernetesJob
    
      sh """set -e
      oc delete job toolbox --ignore-not-found
      sleep 2
      oc create -f job.yaml
      sleep 20 # Adjust the sleep duration to your server velocity
      """
    
      def logs = sh(script: "set -e; oc logs -f job/toolbox", returnStdout: true)
      echo logs
      return logs
    }

    Kubernetes 오브젝트 템플릿

    이 기능은 Kubernetes 오브젝트 템플릿을 사용하여 3scale toolbox를 실행하여 필요에 맞게 조정할 수 있습니다. 3scale toolbox CLI 인수를 설정하고 결과 Kubernetes 작업 정의를 YAML 파일에 쓰고, toolbox의 이전 실행을 정리하고, Kubernetes 작업을 생성하고, 대기합니다.

    • CreatedRunning 상태 간에 포드를 전환해야 하는 시간과 일치하도록 서버 속도에 맞게 대기 기간을 조정할 수 있습니다. 폴링 루프를 사용하여 이 단계를 구체화할 수 있습니다.
    • OpenAPI 사양 파일은 openapi라는 ConfigMap 에서 가져옵니다.
    • 3scale 관리 포털 호스트 이름 및 액세스 토큰은 3scale toolbox 설치 및 액세스 활성화에 표시된 대로 3scale-toolbox 라는 시크릿에서 가져옵니다.
    • ConfigMap 은 파이프라인에서 3단계에서 생성됩니다. 그러나 보안은 이미 파이프라인 외부에 프로비저닝되었으며 보안을 강화하기 위해 RBAC(역할 기반 액세스 제어)가 적용됩니다.
  2. Jenkins 파이프라인 단계에서 3scale toolbox와 함께 사용할 글로벌 환경 변수를 정의합니다. 예를 들면 다음과 같습니다.

    3scale 호스팅

    def targetSystemName = "saas-apikey-usecase"
    def targetInstance = "3scale-saas"
    def privateBaseURL = "http://echo-api.3scale.net"
    def testUserKey = "abcdef1234567890"
    def developerAccountId = "john"

    3scale 온프레미스

    자체 관리 APIcast를 사용하거나 3scale의 온프레미스 설치를 사용하는 경우 다음 두 가지 변수를 선언해야 합니다.

    def publicStagingBaseURL = "http://my-staging-api.example.test"
    def publicProductionBaseURL = "http://my-production-api.example.test"

    변수는 다음과 같이 설명됩니다.

    • targetSystemName: 생성할 서비스의 이름입니다.
    • targetInstance: 3scale toolbox 설치 및 액세스 활성화에서 생성된 3scale 원격 인스턴스의 이름과 일치합니다.
    • privateBaseURL: API 백엔드의 엔드포인트 호스트입니다.
    • testUserKey: 통합 테스트를 실행하는 데 사용되는 사용자 API 키입니다. 표시된 대로 하드 코딩하거나 HMAC 함수에서 생성할 수 있습니다.
    • developerAccountId: 테스트 애플리케이션이 생성될 대상 계정의 ID입니다.
    • publicStagingBaseURL: 생성할 서비스의 공개 스테이징 기반 URL입니다.
    • publicProductionBaseURL: 생성할 서비스의 공개 프로덕션 기본 URL입니다.
  3. 파이프라인 단계를 추가하여 OpenAPI 사양 파일을 가져와 다음과 같이 OpenShift에서 ConfigMap 으로 프로비저닝합니다.

    node() {
     stage("Fetch OpenAPI") {
       sh """set -e
       curl -sfk -o swagger.json https://raw.githubusercontent.com/microcks/api-lifecycle/master/beer-catalog-demo/api-contracts/beer-catalog-api-swagger.json
       oc delete configmap openapi --ignore-not-found
       oc create configmap openapi --from-file="swagger.json"
       """
     }
  4. 3scale 툴박스를 사용하여 API를 3scale로 가져오는 파이프라인 단계를 추가합니다.

    3scale 호스팅

    stage("Import OpenAPI") {
      runToolbox([ "3scale", "import", "openapi", "-d", targetInstance, "/artifacts/swagger.json", "--override-private-base-url=${privateBaseURL}", "-t", targetSystemName ])
    }

    3scale 온프레미스

    자체 관리 APIcast를 사용하거나 3scale의 온프레미스 설치를 사용하는 경우 공용 스테이징 및 프로덕션 기반 URL에 대한 옵션도 지정해야 합니다.

    stage("Import OpenAPI") {
      runToolbox([ "3scale", "import", "openapi", "-d", targetInstance, "/artifacts/swagger.json", "--override-private-base-url=${privateBaseURL}", "-t", targetSystemName, "--production-public-base-url=${publicProductionBaseURL}", "--staging-public-base-url=${publicStagingBaseURL}" ])
    }
  5. toolbox를 사용하여 3scale 애플리케이션 계획 및 애플리케이션을 생성하는 파이프라인 단계를 추가합니다.

    stage("Create an Application Plan") {
      runToolbox([ "3scale", "application-plan", "apply", targetInstance, targetSystemName, "test", "-n", "Test Plan", "--default" ])
    }
    
    stage("Create an Application") {
      runToolbox([ "3scale", "application", "apply", targetInstance, testUserKey, "--account=${developerAccountId}", "--name=Test Application", "--description=Created by Jenkins", "--plan=test", "--service=${targetSystemName}" ])
    }
    stage("Run integration tests") {
      def proxyDefinition = runToolbox([ "3scale", "proxy", "show", targetInstance, targetSystemName, "sandbox" ])
      def proxy = readJSON text: proxyDefinition
      proxy = proxy.content.proxy
    
      sh """set -e
      echo "Public Staging Base URL is ${proxy.sandbox_endpoint}"
      echo "userkey is ${testUserKey}"
      curl -vfk ${proxy.sandbox_endpoint}/beer -H 'api-key: ${testUserKey}'
      curl -vfk ${proxy.sandbox_endpoint}/beer/Weissbier -H 'api-key: ${testUserKey}'
      curl -vfk ${proxy.sandbox_endpoint}/beer/findByStatus/available -H 'api-key: ${testUserKey}'
      """
    }
  6. toolbox를 사용하여 API를 프로덕션 환경으로 승격하는 단계를 추가합니다.

    stage("Promote to production") {
      runToolbox([ "3scale", "proxy", "promote", targetInstance,  targetSystemName ])
    }