반응형

설명

  • jenkins pipeline 코드 작성시 자주 사용되는 코드들 정리
  • Pipeline Utility Steps 플러그인 모듈도 포함

tools

  • Nodejs 플러그인 설치
  • Global Tool Configuration에서 NodeJS Installs 추가
    • Name : nodejs-13.10.1
    • Version: NodeJS 13.10.1
    • Force 32bit architecture : 체크
pipeline {
    agent any
    tools { nodejs "nodejs-13.10.1" }

    stages {
        stage("example") {
            steps {
                script {
                    sh "npm install -g yarn"
                    sh "yarn --version"
                }
            }
        }
    }
}

parameters

pipeline {
    agent any

    parameters {
        string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
        text(name: 'BIOGRAPHY', defaultValue: '', description: 'Enter some information about the person')
        booleanParam(name: 'TOGGLE', defaultValue: true, description: 'Toggle this value')
        choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')
        password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'Enter a password')
    }

    stages {
        stage("example") {
            steps {
                script {
                    echo "Hello ${params.PERSON}"
                    echo "Biography: ${params.BIOGRAPHY}"
                    echo "Toggle: ${params.TOGGLE}"
                    echo "Choice: ${params.CHOICE}"
                    echo "Password: ${params.PASSWORD}"
                }
            }
        }
    }
}

input

pipeline {
    agent any

    stages {
        stage("example") {
            steps {
                script {
                    def parameters = input(
                        message: "I'm test input",
                        parameters: [
                            string(name: "value1", defaultValue: "", description: ""),
                            booleanParam(name: "value2", defaultValue: true, description: ""),
                            choice(name: "value3", choices: ["aaa", "bbb"], description: ""),
                            credentials(name: "value4", defaultValue: "test-repository", description: ""),
                            file(name: "value5", description: ""),
                        ]
                    )

                    println parameters.value1
                    println parameters.value2
                    println parameters.value3
                    println parameters.value4
                    println parameters.value5
                }
            }
        }
    }
}

sshagent

// SSH Agent 플러그인 필요
sshagent(credentials: ["my-credential-id"]) {
    sh "git clone git@github.com:test-user/test-repository.git"
}

 

withCredentials

withCredentials([string(credentialsId: "my-credential-id", variable: "TOKEN")]) {
    httpRequest(
        httpMode: "GET",
        url: "https://api.test.com",
        contentType: "APPLICATION_JSON_UTF8",
        customHeaders: [[name: "Authorization", value: "token ${TOKEN}"]],
        consoleLogResponseBody: true,
        timeout: 5000
    )
}

dir

sh "pwd"
sh "mkdir -p temp/repo"

dir("temp/repo") {
    sh "pwd"
}

httpRequest

import groovy.json.JsonOutput

def body = [
    title: "title",
    body: "body",
    head: "develop",
    base: "master"
]

// Http Request 플러그인 필요
def result = httpRequest(
    httpMode: "GET",
    url: "https://api.github.com/repos/test-user/test-repository/pulls",
    contentType: "APPLICATION_JSON_UTF8",
    customHeaders: [[name: "Authorization", value: "token 1a35c322bf25a98dca3d104c5fe0d43b3fbd3c9c"]],
    consoleLogResponseBody: true,
    requestBody: JsonOutput.toJson(body),  // JsonOutput은 한글 깨짐 현상이 발생하므로 주의
    timeout: 5000
)

// jenkins.plugins.http_request.ResponseContentSupplier
println result.getClass()
println result.getStatus()
println result.getHeaders()
println result.getCharset()
println result.getContent()

writeFile

// Pipeline Utility Steps 플러그인 필요
writeFile(file: "test.txt", text: "Hello World", encoding: "UTF-8")

readFile

// Pipeline Utility Steps 플러그인 필요
def text = readFile(file: "test.txt")

writeJSON

// Pipeline Utility Steps 플러그인 필요
writeJSON(file: "test.json", json: "{message: 'Hello World'}", pretty: 4)

readJSON

// Pipeline Utility Steps 플러그인 필요
def data1 = readJSON(file: "test.json")
def data2 = readJSON(text: "{message: 'Hello World'}")

writeYaml

// Pipeline Utility Steps 플러그인 필요
writeYaml(file: "test.yaml", data: "aaa: 안녕하세요\nbbb: Hello World")

readYaml

// Pipeline Utility Steps 플러그인 필요
def data1 = readYaml(file: "test.yaml")
def data2 = readYaml(text: "aaa: 안녕하세요\nbbb: Hello World")

zip

// Pipeline Utility Steps 플러그인 필요
zip(
    zipFile: "test.zip",
    dir: ".",   // optional
    glob: "**/*.json"   // optional
)

unzip

// Pipeline Utility Steps 플러그인 필요
unzip(
    zipFile: "test.zip",
    dir: "test",    // optional
    glob: "**/*.json"   // optional
)

findFiles

// Pipeline Utility Steps 플러그인 필요
def files = findFiles(
    glob: "**/*.json"   // optional
)

// org.jenkinsci.plugins.pipeline.utility.steps.fs.FileWrapper
files.each { file ->
    println file.name
    println file.path
    println file.directory
    println file.length
    println file.lastModified
}

fileExists

// Pipeline Utility Steps 플러그인 필요
def isExists = fileExists("test.json")

gitRefsParameter - custom

def parameters = input(
    message: "Parameters",
    parameters: [
        gitRefsParameter(
            name: "branch",
            description: "대상 브랜치",
            defaultValue: "develop",
            type: "BRANCH",
            sort: "DESC",
            credentialId: "test-repository-id",
            remoteUrl: "git@github.com:test-user/test-repository.git"
        )
    ]
)

println parameters.branch
import hudson.model.ChoiceParameterDefinition

def call(Map params) {
    Map TYPE_MAP = [
        TAG: "tags",
        BRANCH: "heads"
    ]

    String refType = TYPE_MAP[params.type] ? TYPE_MAP[params.type] : "heads"

    sshagent(credentials: [params.credentialId]) {
        String output = sh(script: "git ls-remote --${refType} ${params.remoteUrl} | sed 's?.*refs/${refType}/??'", returnStdout: true)

        List refs = (output) ? output.split("\n") as List : []

        params.choices = (params.sort == "ASC") ? refs.sort() : refs.reverse()
    }

    return new ChoiceParameterDefinition(
        params.name,
        params.choices,
        params.defaultValue ? params.defaultValue : params.choices[0],
        params.description
    )
}
반응형

'Development > Jenkins' 카테고리의 다른 글

[Jenkins] docker image 빌드 설정  (0) 2023.01.18
[Jenkins] Ansible 연동  (0) 2020.12.28
[Jenkins] Jenkinsfile  (0) 2020.12.28
[Jenkins] Selenium 테스트 설정  (0) 2019.11.24
[Jenkins] Publish Over SSH 설정  (0) 2019.05.01

+ Recent posts