Skip to main content

Command Palette

Search for a command to run...

Jenkins Pipeline Declarative 문법 정리

Updated
Jenkins Pipeline Declarative 문법 정리
K

backend developer interested in technical problem

g자꾸 Declarative와 Scripted가 뭐고 헷갈려서 정리용으로 씁니다.. 하지만 둘의 차이점을 다루기 보다는 이 글에선 Declarative 문법에 대해서 다룹니다.

파이프라인 구조

예시

예시1

pipeline {
    agent any 
    stages {
        stage('Stage 1') {
            steps {
                echo 'Hello world!' 
            }
        }
    }
}
  1. pipeline : 젠킨스 파이프라인 플러그인을 호출하기 위한 필수 외부 블록

  2. agent : 파이프라인을 실행하고 싶은 위치 정의any : 파이프라인이나 스테이지를 실행하기 위해 사용가능한 어느 agent도 사용 할 수 있음 정의

  3. echo : 간단한 console output 을 찍을 수 있다.

  4. stages : stage의 모음

  5. steps : 실제 작업 수행하는 블록

  6. 세미콜론은 없습니다

예시2

  • post : 파이프라인 실행 또는 스테이지 끝에 실행될 동작을 정의(always, changed, failure, success, unstable, aborted)
pipeline {
    agent any

    stages {
        stage('build') {
            steps {
                sh 'build check'
            }
        }
    }

    post {
        always {
            junit '**/target/*.xml'
        }
        failure {
            mail to: team@gmail.com, subject: 'Pipeline fail email'
        }
    }
}

섹션

agent : 젠킨스잡을 실행할 agent

필수여부필수
파라미터• any : 사용가능한 agent
• none : global agent는 설정되지 않음. 대신 각 stage에 설정 필요
• label : 특정 label 명으로 된 environment로 설정
• node : label과 유사
• docker : 특정 도커 이미지로 수행
• dockerfile : 도커 파일 기반으로 수행
위치• pipeline top level(필수)
• stage block(선택)

post : 특정 스테이지 이전 혹은 이후에 실행될 condition block

필수여부선택
파라미터• always : 실행 끝나고나서 실행되는 step
• changed : previous run과 다른 status이면 실행되는 step
• failure : 실패하면 실행되는 step
• success : 성공하면 실행되는 step
• unstable : test fail, code violation 등일때 실행되는 step
• aborted : 강제로 중지됬을 때 실행되는 step
위치• pipeline top level(선택)
• stage block(선택)
pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                echo 'Hello World'
            }
        }
    }
    post { 
        always { 
            echo 'It's Nice to meet youuuuuuu'
        }
    }
}

stages : 스테이지들을 모아놓은곳

필수여부필수
위치• pipeline block에서 단 한번
pipeline {
    agent any
    stages { 
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}

steps : 각 stage 내부블록에서 여러번 선언할 수 있는 블록

필수여부필수
위치• 각 stage block에서 여러번

Directives

enviroment : key-value style로 파이프라인 내부에서 사용할 변수로 선언 가능

필수여부선택
위치• 파이프라인 혹은 스테이지 블락 내부
pipeline {
    agent any
    environment { 
        Name = 'Geonhyeon'
    }
    stages {
        stage('Checkout') {
            environment { 
                PAT_TOKEN = credentials('my-git-token') 
            }
            steps {
                sh 'printenv'
            }
        }
    }
}

options : pipeline의 옵션을 삽입 가능

필수여부선택
위치• 파이프라인 블락 안쪽 단 한번

사용가능한 옵션들

  • buildDiscarder : Persist artifacts and console output for the specific number of recent Pipeline runs

  • disableConcurrentBuilds : Disallow concurrent executions of the Pipeline. Can be useful for preventing simultaneous accesses to shared resources, etc

  • overrideIndexTriggers : Allows overriding default treatment of branch indexing triggers

  • skipDefaultCheckout : Skip checking out code from source control by default in the agent directive

  • skipStagesAfterUnstable : Skip stages once the build status has gone to UNSTABLE

  • checkoutToSubdirectory : Perform the automatic source control checkout in a subdirectory of the workspace

  • timeout : Set a timeout period for the Pipeline run, after which Jenkins should abort the Pipeline

  • retry : On failure, retry the entire Pipeline the specified number of times

  • timestamps : Prepend all console output generated by the Pipeline run with the time at which the line was emitted

pipeline {
    agent any
    options {
        timeout(time: 1, unit: 'HOURS') 
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}

parameteres : 유저로부터 트리거링 받은 변수들에 대해서 선언할 수 있다.

필수여부선택
위치• 파이프라인 블락 안쪽 단 한번
  • String : A parameter of a string type, for example: parameters { string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: '') }

  • booleanParam : A boolean parameter, for example: parameters { booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: '') }

triggers : cront, pollSCM, upstream 등 여러방식으로 트리거를 구성할 수 있다.


환경변수

1. env관련 환경변수 (env.로 접근)

env 환경 변수는 다음과 같은 형식 env.VARNAME으로 참조될 수 있다. 대표적인 env의 property는 아래와 같다.

property (환경변수 이름)설명
env.BUILD_ID현재 빌드의 ID이며 이는 v1.597 이상에서는 BUILD_NUMBER와 같은 값을 가진다
env.JOB_NAME현재 빌드중인 프로젝트의 이름으로 foo 또는 foo/bar와 같은 형식이다.
env.BRANCH_NAMEmultibranch 프로젝트인 경우 사용할 수 있으며, 현재 빌드되고 있는 브랜치명을 알려준다
env.CHANGE_IDmultibranch 프로젝트의 change request에 대한 change ID(PR number)를 나타낸다.
env.CHANGE_URLmultibranch 프로젝트의 change request에 대한 change URL을 나타낸다.
env.CHANGE_TARGETmultibranch 프로젝트의 change request에 대해 merge될 base branch를 나타낸다.
env.CHANGE_BRANCHmultibranch 프로젝트의 change request에 대해 현재 HEAD가 가리키고 있는 브랜치 명을 알려준다. 이는 BRANCH_NAME과 같을 수 있다.
env.BUILD_NUMBER현재 build number를 나타낸다.
env.WORKSPACE특정 디렉토리에 대한 절대 경로. 이 특정 디렉토리는 빌드를 위해 workspace로써 할당됨.
env.JENKINS_HOME특정 디렉토리에 대한 절대 경로. 이 특정 디렉토리는 controller file system위에 할당됨 (젠킨스가 데이터를 저장하기 위해)
env.JENKINS_URLhttp://server:port/jenkins/와 같은 jenkins의 URL을 알려준다.
env.BUILD_URLhttp://server:port/jenkins/job/foo/15/와 같은 현재 build의 URL을 알려준다.
env.JOB_URLhttp://server:port/jenkins/job/foo/와 같은 job의 URL을 알려준다

2. currentBuild

currentBuild 변수는 RunWrapper 타입입니다. 현재 진행중인 빌드를 참고하는 데 사용됩니다.

이것은, 읽는게 가능한 아래의 property들을 가지고 있습니다. currentBuild로 접근 가능.

property (환경변수 이름)설명
getBuildCause
number빌드 번호 (integer)
result보통 SUCCESS, UNSTABLE, 혹은 FAILURE (진행중인 빌드에 대해선 null을 반환할 수 있음)
currentResult보통 SUCCESS, UNSTABLE, 혹은 FAILURE. null이 절대로 될 수 없음.
displayName보통 #123 하지만, 때론 SCM commit identifier가 설정되기도 함.
fullDisplayName보통 folder >> folder 2 >> foo #123.
projectName이 빌드의 프로젝트 이름, 예를 들어 foo.
description추가적인 정보, (빌드에 대한)
id보통 number (문자열로 되어있음)
changeSet뚜렷한 SCM 체크아웃들로부터 오는 changesets의 목록
keepLog만약 true이면, 이 빌드에 대한 로그 파일이 유지됨, 즉 지워지지 않음.

More from this blog

rfc 959 읽어보면서 ftp이해하기

들어가며 프로젝트에서 FTP를 통해 파일을 전송하는 클라이언트를 개발했을 때 이야기입니다. 프로토콜에 대한 이해 없이 개발을 진행하다 보니 불필요하게 시간을 소모한 경험이 있어서 RFC 원문을 읽어보게 되었습니다. 읽게 된 계기 당시 FTP 프로토콜에 대한 이해가 부족한 상태로 개발을 시작했습니다. '제어를 위한 포트와 데이터 전송을 위한 포트가 분리되어 있다' 정도만 알고 있었고 Active 모드와 Passive 모드의 차이를 제대로 이해...

Dec 5, 20256
rfc 959 읽어보면서 ftp이해하기

mapstruct 로 보일러플레이트 코드 줄이기

배경 사내에서 교통 모니터링용 레이더 디바이스를 관리하는 API를 개발했을때 이야기입니다. 반복되는 코드에서 느꼈던 피로를 개선하고자 mapstruct를 적용해봤습니다. 실황 우선 일부 필드만 추출한 Device에 대해 간단히 이야기해야할 것 같습니다. 교통 모니터링용 레이더 디바이스로 신호등이나 가로등에 설치하며 설치된 좌표를 기록하는 위도, 경도와 레이더가 바라보는 방향을 의미하는 heading_angle필드 등이 있습니다. public...

Nov 13, 20259
mapstruct 로 보일러플레이트 코드 줄이기
T

takoyakisoba

38 posts