파이프라인에 테스트 결과 추가 및 스크립트 빌드

신규 또는 기존 테스트 및 빌드 스크립트의 결과를 DevSecOps 파이프라인 지속적 통합 흐름에 추가하여 기존 테스트 및 빌드 플로우를 지속적 통합 파이프라인에 연결합니다.

파이프라인이 시작될 때 DevSecOps 스크립트는 애플리케이션 및 구성 리포지토리를 다음 디렉터리에 자동으로 복제합니다:

  1. 애플리케이션 리포지토리는 경로에 복제됩니다 /workspace/app/<APP_REPO_NAME>

  2. 파이프라인 구성 리포지토리는 다음 경로에 복제됩니다 /workspace/app/one-pipeline-config-repo

어느 단계에서든 이러한 리포지토리에 있는 스크립트를 실행해야 하는 경우 먼저 해당 디렉터리로 이동해야 합니다. 다음 방법 중 하나를 사용하여 이 작업을 수행할 수 있습니다:

  1. 복제된 리포지토리 경로를 직접 사용하기
  • 앱 리포지토리: cd "${WORKSPACE}/$APP_REPO_NAME"

  • 구성 리포지토리: cd "${WORKSPACE}/one-pipeline-config-repo/"

  1. Load_repo 명령 사용
  • 앱 리포지토리: cd "${WORKSPACE}/$(load_repo app-repo path)"

  • 구성 리포지토리: cd "${WORKSPACE}/$(load_repo one-pipeline-config-repo path)"

wORKSPACE는 루트 경로 /workspace/app를 가리킵니다.

지속적 통합 파이프라인 내에서 다음 스테이지를 사용하여 테스트 및 빌드 단계를 추가할 수 있습니다.

  • 설정
  • 테스트
  • 컨테이너화 (빌드)
  • 릴리스

파이프라인 설정

설정 단계를 사용하여 테스트 및 빌드 환경을 설정하고 정보를 파이프라인으로 가져옵니다. 예를 들어, 단일 빌드에서 여러 개의 앱 관련 저장소를 사용할 수 있습니다. 필요한 모든 리포지토리를 복제하고 규정 준수 관련 검사 및 스캔에서 해당 리포지토리를 파이프라인이 인식하도록 할 수 있습니다.

내부적으로 파이프라인에 의해 복제되고 참조 이름 app-repo 과 함께 save_repo pipelinectl 인터페이스를 사용하여 파이프라인에 추가되는 기본 앱 리포지토리입니다. 도구 체인 템플리트에서 파이프라인을 설정하는 경우 기본 저장소는 저장소 파이프라인 UI 매개변수로 제공되거나 도구 체인 바인딩 이름으로 선택됩니다.

더 많은 리포지토리를 사용하려면 설정 단계에서 리포지토리를 복제하고 동일한 save_repo 인터페이스를 사용하여 파이프라인에 추가하세요.

#
# your scripts cloning the repositories
#
# make sure you prepare or export the following data from each cloned repository:
# - repository URL
# - path where it was cloned, relative to the $WORKSPACE path
# - cloned branch
# - latest commit hash
#
your_clone_scripts

#
# when cloning is complete
# use `save_repo` to add these information to the pipeline
# repo-reference-name can be any name, it is used to refer to the stored repo
#
save_repo <repo-reference-name> \
    url="${REPO_URL}" \
    path="${REPO_PATH}" \
    branch="${CLONED_BRANCH}" \
    commit="${LATEST_GIT_COMMIT}"

이러한 방식으로 나머지 파이프라인은 해당 저장소에서 규제 준수 위반 및 취약성을 스캔할 수 있습니다.

save_repo 을 사용하여 저장하는 경로는 워크스페이스 경로에 상대적이어야 합니다.

스크립트 또는 기본 이미지를 위해 pipelinectl 도구를 설치할 필요가 없습니다. 참조 파이프라인은 스크립트 컨텍스트의 바이너리를 제공합니다.

테스트

이 스테이지에서는 코드 저장소에 대한 테스트를 실행합니다. list_reposload_repo pipelinectl 인터페이스를 사용하여 설정 단계에서 추가한 리포지토리에 액세스할 수 있습니다.

exit_code=0

#
# `list_repos` returns the list of the reference names of saved repos
#
list_repos | while IFS= read -r repository ; do

    #
    # load_repo returns a property of a saved repository
    #
    # Usage:
    # load_repo <repo-reference-name> <property>
    #
    url="$(load_repo "$repository" url)"
    sha="$(load_repo "$repository" commit)"
    branch="$(load_repo "$repository" branch)"
    path="$(load_repo "$repository" path)"

    #
    # use your repos to test, etc
    #
    run_tests
    result=$?

    if [ $result != 0 ]; then
        exit_code=$result
    fi
done

exit $exit_code

단위 테스트 준수 제어는 스테이지 스크립트의 종료 코드를 기반으로 합니다. 테스트가 성공하면 0 으로 종료하십시오. 그렇지 않으면 끝에 0이 아닌 종료 코드를 리턴합니다.

결과 저장

테스트에서 JSON 또는 XML로 된 테스트 결과와 같은 일부 보고서 아티팩트가 생성될 수 있습니다. 이 단계에서 save_result pipelinectl 인터페이스를 사용하여 작성된 준수 증거에 테스트를 증거 아티팩트로 첨부하십시오.

#
# run tests with some test suite runner, and save output to results.json
#
test_runner -o results.json

#
# save the result for the pipeline, so it can attach it to the unit test evidence
#
save_result test results.json

save_results의 첫 번째 매개변수는 DevSecOps 파이프라인 구성 스테이지 이름(test, scan-artifact 또는 acceptance-test)이어야 합니다. 그렇지 않으면 증거 수집가가 이를 찾아 적절한 증거에 첨부할 수 없습니다.

save_result pipelinectl 인터페이스를 사용하면 파이프라인이 결과 아티팩트를 찾아 증거 보관함에 업로드하고 파이프라인에서 생성한 규정 준수 증거에 첨부할 수 있습니다.

save_result를 사용하는 동안 단위 테스트에 대해 작성된 예제 증거:

{
  "evidence_type_id": "com.ibm.unit_tests",
  "evidence_type_version": "1.0.0",
  "date": "2021-03-31T07:41:31.881Z",
  "result": "success",
  "pipeline_id": "8c2b6750-91db-45fb-98ee-51684843b821",
  "pipeline_run_id": "89a04de9-2795-4e8e-be90-52a92ac7f9c1",
  "issues": [],
  "artifacts": [
    {
      "url": "https://s3.us-south.cloud-object-storage.appdomain.cloud/cos-bucket-name/ci/89a04de9-2795-4e8e-be90-52a92ac7f9c1/artifacts/compliance-app-COMPACT-20210218231513608/unit-tests-results.json_d9619521e7444fef0ff052e59fd54049",
      "hash": "d9619521e7444fef0ff052e59fd54049"
    }
  ],
  "toolchain_crn": "crn:v1:bluemix:public:toolchain:us-south:a/40111714589c4f7099032529b26a7a63:39d4f080-55e5-42ee-a787-26d936fb2b97::",
  "log": [
    {
      "url": "https://cloud.ibm.com/devops/pipelines/tekton/8c2b6750-91db-45fb-98ee-51684843b821/runs/89a04de9-2795-4e8e-be90-52a92ac7f9c1/code-unit-tests/run-stage?env_id=ibm:yp:us-south",
      "hash": null
    },
    {
      "url": "https://s3.us-south.cloud-object-storage.appdomain.cloud/cos-bucket-name/ci/89a04de9-2795-4e8e-be90-52a92ac7f9c1/artifacts/logs/code-unit-tests/run-stage.log_dae902fb1455b1fc9c565273aa4fe1bc",
      "hash": "dae902fb1455b1fc9c565273aa4fe1bc"
    }
  ]
}

빌드 또는 컨테이너화

이 단계에서는 아티팩트를 만들 수 있습니다. 파이프라인은 도커 이미지 유형 아티팩트에 대한 몇 가지 기본 기능을 제공하지만 여기에서 모든 아티팩트를 빌드할 수 있습니다. 나중에 스캔을 실행할 수 있도록 파이프라인에 대해 작성된 아티팩트를 저장하거나 릴리스 단계에서 아티팩트를 사용하십시오.

빌드된 아티팩트에 관한 정보를 제공하려면 save_artifact pipelinectl 인터페이스를 사용하십시오.

#
# your scripts building the artifact
#
# make sure you prepare or export the following data from each built artifact:
# - type (image for docker images, package for rpms, npm tarballs, etc )
# - full artifact URL with version tag
# - artifact digest
#
your_build_scripts

#
# when the build is complete
# use `save_artifact` to add these information to the pipeline
# artifact-reference-name can be any name, it is used to refer to the stored artifact
#
save_artifact <artifact-reference-name> \
    type=image" \
    name="${IMAGE_URL}" \
    digest="${IMAGE_DIGEST}"

이미지 이름의 기본 형식은 image-URL:build-tag 입니다.

Docker 이미지를 빌드하는 경우 save_artifact 인터페이스를 사용하여 기본 제공 이미지 서명 및 CR IBM Informix 가상 기기 스캔 작업을 위해 해당 이미지를 전송합니다.

릴리스

파이프라인의 끝에서 빌드된 아티팩트를 인벤토리에 추가해야 배치로 승격할 수 있습니다. release 스테이지는 인벤토리에 기타 아티팩트(예: Helm 차트)를 추가하려는 경우 유연성을 제공합니다.

이 스테이지에서는 CLI cocoa inventory add 명령과 pipelinectl 명령의 데이터를 사용하여 인벤토리 항목을 작성할 수 있습니다.

파이프라인 실행에 문제가 있는 경우 문제가 되는 재고를 방지하기 위해 재고 업데이트를 건너뛰도록 선택할 수 있습니다. 자원 명세 갱신을 건너뛰려면 다음 환경 변수를 사용하십시오.

  • skip-inventory-update-on-failure 인벤토리가 업데이트되는지 여부를 지정하기 위한 파이프라인의 옵트 인 환경 변수입니다.
  • one-pipeline-status 파이프라인 실행에 단계 실패가 있는 경우 1 로 설정하십시오.

이 단계에서 cocoa inventory add 를 호출하기 전에 이러한 변수를 확인하십시오.

# Check the status of pipeline and then release the artifacts to inventory

ONE_PIPELINE_STATUS=$(get_env one-pipeline-status 0)
if [ -n "$(get_env skip-inventory-update-on-failure "")" ]; then
    if [ $ONE_PIPELINE_STATUS -eq 1 ]; then
          echo "Skipping release stage as some of the pipeline stages are not successful."
          exit 1
    fi
fi

#
# `list_artifacts` returns the list of the reference names of saved artifacts
#
list_artifacts | while IFS= read -r artifact ; do
    #
    # Add a new value to the inventory repository. `cocoa inventory add` creates a new file with the name option,
    # if does not exist otherwise overwrites it.
    #
    cocoa inventory add \
        --name="${artifact}" \
        --artifact="$(load_artifact $artifact name)" \
        --repository-url="$(load_repo app-repo url)" \
        --commit-sha="$(load_repo app-repo commit)" \
        --build-number="${BUILD_NUMBER}" \
        --pipeline-run-id="${PIPELINE_RUN_ID}" \
        --version="$(get_env version)" \
        --app-artifacts="{ \
            \"signature\": \"$(load_artifact $artifact signature)\", \
            \"provenance\": \"$(load_artifact $artifact name)\"\
        }"
done

CLI를 사용하려면 스크립트에 설치하거나 CLI가 미리 설치되어 있는 기본 이미지를 사용해야 합니다.