JenkinsFile個人的チートシート


JenkinsFileを書くときに色々思い出すための個人的なメモです。

手元で試すための環境

docker run -p 8080:8080 -v /Users/yy_yank/jenkins:/var/jenkins_home jenkins

チートシート

ステージを指定したい

stage("任意のステージ名")


stage('prepare'){
    // prepare...
}

stage('test'){
    // test...
}

stage('build'){
    // build...
}


マスター/スレーブを指定したい

node("マスター or スレーブ名")

stage('windowsでなにかする') {
    node('windows') {
        // do something
    }
}

node名前の引数を省略するとマスターになるっぽい。

stage('masterでなにかする') {
    node{
        // ここはマスター
    }
}

ファイルの存在チェック

fileExists "ファイルパス"

if(fileExists("./${target}")) {
  echo "file exists ${target}"
}

ファイル作りたい

writeFile "ファイルパス"

stage('write') {
    node{
        writeFile file:"./hogehoge.txt", text:"hogehoge~",  encoding:"UTF-8"
    }
}

node内でやらないとどこに書いていいかわかんないよ的な感じにエラーになる。

Started by user yy_yank
[Pipeline] stage
[Pipeline] { (write)
[Pipeline] writeFile
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing

ディレクトリを消す

dir('ディレクトリ名')でディレクトリを指定してdeleteDir()

dir('target') {
    deleteDir()
}

ジョブのartifactsを生成したい

archiveArtifacts

Pipeline Examples より引用:

// This shows a simple example of how to archive the build output artifacts.
node {
    stage "Create build output"

    // Make the output directory.
    sh "mkdir -p output"

    // Write an useful file, which is needed to be archived.
    writeFile file: "output/usefulfile.txt", text: "This file is useful, need to archive it."

    // Write an useless file, which is not needed to be archived.
    writeFile file: "output/uselessfile.md", text: "This file is useless, no need to archive it."

    stage "Archive build output"

    // Archive the build output artifacts.
    archiveArtifacts artifacts: 'output/*.txt', excludes: 'output/*.md'
}

ジョブを失敗させたい

error "エラーメッセージ"

stage('test') {
    node {
        if(fileExists("./あやしいファイル.txt")) {
            error "このファイルはダメ!"
        }
    }
}

入力待ち状態にしたい

input

stage('write') {
    node{
        writeFile file:"./hogehoge.txt", text:"hogehoge~",  encoding:"UTF-8"
    }
}

stage('failure') {

    node {
        input "心の準備はOK?"
        if(fileExists ("./hogehoge.txt")) {
            error "このファイルはダメ!"
        }
    }
}

echo使いたい

そのままecho使える

stage ('echo') {
    echo "\( 'ω')/ウオオオオオアアアーーーッ!"
}

シェルを実行したい

sh "コマンド"

sh 'cat nyaan.txt'

Jenkinsに登録してある認証情報を使いたい

withCredentialsを使う

withCredentials(
           [[$class: 'UsernamePasswordMultiBinding', 
             credentialsId: 'test',
             usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]
) {
        sh 'echo uname=$USERNAME pwd=$PASSWORD'
}

環境変数をサッと使いたい

withEnvを使う

Pipeline Examples より引用:

withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
}

parallel実行したい

parallel

Using a Jenkinsfile より引用:

stage('Test') {
    parallel linux: {
        node('linux') {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
        }
    },
    windows: {
        node('windows') {
            /* .. snip .. */
        }
    }
}

ちょっとジョブを止めたい

sleepを使う

stage ('ムスカ') {
    echo "3分間待ってやる"
    sleep 180
}

不安定な処理とかを何回か処理させたい

retryを使う

retry(10) {
    // some block
}

特定の状態になるまで待つ

waitUntilを使う。

画面が表示されるまで待つ

waitUntil {
    try {
        sh 'wget -q http://localhost:8080 -O /dev/null'
        return true
    } catch (exception) {
        return false
    }
}

タイムアウトを設定する

timeoutを使う

timeout(120){
    waitUntil {
        try {
            sh 'wget -q http://localhost:8080 -O /dev/null'
            return true
        } catch (exception) {
            return false
        }
    }
}

メールを送信したい

mailを使う

mail bcc: '[email protected]', body: 'this is mail body', cc: '[email protected]', from: '', replyTo: '', subject: 'this is mail subject', to: '[email protected]'

pluginを使いたい

JenkinsPipelineコンパチなものなら使える

参考:
Plugin Compatibility with Pipeline

  • git
git([
    credentialsId: 'gitの認証情報でjenkinsに登録してるid',
    url          : 'http://hogehoge.git',
    branch       : 'master'
])

色々思いつかない時は

http://{ホスト名}/job/{ジョブ名}/pipeline-syntax/
とかを見るとGUIから選択形式でスクリプトを生成できる

参考URL

https://jenkins.io/doc/book/pipeline/syntax/
https://jenkins.io/doc/pipeline/examples/
https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/
http://qiita.com/comefigo/items/fc7aad310235caf89fcd
http://arasio.hatenablog.com/entry/2016/10/07/005055
http://be-hase.hatenablog.com/entry/2016/04/28/175311