Jenkins 실무 가이드 · Part 3

Jenkinsfile 실무 패턴

빌드 절차를 Jenkinsfile로 저장해 리뷰 가능한 자동화 코드로 만들기

작성 기준2026년 7월

이 파트에서 다루는 내용

Declarative Pipeline 기본 구조Stage 분리Credentials 사용브랜치와 배포 조건
01

Jenkinsfile은 빌드 절차의 소스 코드입니다

Jenkinsfile은 Git 저장소에 함께 두는 파이프라인 정의 파일입니다. 누가 어떤 빌드 절차를 바꿨는지 코드 리뷰와 커밋 이력으로 확인할 수 있습니다.

초기에는 checkout, install, test, build, archive 정도만 명확히 나눠도 충분합니다.

기본 Declarative Pipelinegroovy
pipeline {
  agent any

  options {
    timestamps()
    buildDiscarder(logRotator(numToKeepStr: "20"))
  }

  stages {
    stage("Checkout") {
      steps {
        checkout scm
      }
    }

    stage("Install") {
      steps {
        bat "npm.cmd ci"
      }
    }

    stage("Test") {
      steps {
        bat "npm.cmd test"
      }
    }

    stage("Build") {
      steps {
        bat "npm.cmd run build"
      }
    }
  }
}

Windows agent 기준 예시입니다. Linux agent라면 bat 대신 sh를 사용합니다.

02

Stage 이름은 장애 위치를 바로 보여줘야 합니다

  • Checkout, Install, Test, Build, Package, Deploy처럼 사람이 읽고 바로 이해할 수 있는 이름을 씁니다.
  • 모든 명령을 한 stage에 몰아넣으면 실패 위치를 찾기 어렵습니다.
  • 테스트와 빌드는 분리합니다. 테스트 실패와 빌드 실패는 대응 방식이 다릅니다.
  • 배포는 가능하면 별도 stage로 분리하고 main 브랜치 또는 승인 조건을 둡니다.
03

Credentials는 로그에 노출하지 않습니다

토큰과 비밀번호를 Jenkinsfile에 직접 쓰면 저장소에 비밀정보가 남습니다. Jenkins Credentials에 저장하고, 파이프라인에서는 credentialsId로 참조합니다.

Credentials 사용 예시groovy
pipeline {
  agent any

  stages {
    stage("Deploy") {
      when {
        branch "main"
      }
      steps {
        withCredentials([string(credentialsId: "deploy-token", variable: "DEPLOY_TOKEN")]) {
          bat "deploy.cmd"
        }
      }
    }
  }
}

deploy.cmd 안에서도 토큰을 echo하지 않도록 주의합니다.

금지

Jenkinsfile, 배포 스크립트, 빌드 로그에 토큰 값을 직접 남기지 않습니다.

04

post 블록으로 결과 처리를 고정합니다

빌드가 성공하든 실패하든 항상 해야 하는 후처리가 있습니다. 테스트 리포트 수집, 산출물 보관, 알림, 워크스페이스 정리 같은 작업은 post 블록에 둡니다.

결과 수집 예시groovy
post {
  always {
    junit allowEmptyResults: true, testResults: "reports/**/*.xml"
    archiveArtifacts allowEmptyArchive: true, artifacts: "dist/**"
  }
  failure {
    echo "Build failed. Check test reports and console log."
  }
}
체크

이 파트 완료 기준