LoginSignup
1
2

More than 3 years have passed since last update.

Jenkinsfile は Groovy 文としてどう解釈されるのか? (未完)

Posted at

JSON や YAML と違って、Jenkinsfile に纏わり付く気持ち悪い雰囲気は、Jenkinsfile がただのデータではなく Groovy というプログラミング言語だからだろう。プログラミング言語なので設定ファイルの中で何でも出来てしまうのは便利な一方で、一歩間違えれば良からぬことが起こってしまうのでは無いかという潜在的な恐怖がある。その恐怖を克服するため、Groovy についてちょっと調べてみた。

Jenkins のインストールと Pipeline の作成

なんとなくインストーラを使わずに Jenkins を設定してみる。

https://jenkins.io/download/ より Generic Java package をダウンロード

java -jar jenkins.war

http://localhost:8080 にブラウザでアクセスして適当に初期化する。

https://jenkins.io/doc/book/pipeline/getting-started/ の通りに example-pipeline 作成して以下の Pipeline を作成する。

pipeline {
    agent any 
    stages {
        stage('Stage 1') {
            steps {
                echo 'Hello world!' 
            }
        }
    }
}

Build Now でこの Pipeline をを実行出来る。

Jenkins にコマンドラインからアクセスする

いちいち Build Now を押すのは面倒なので、 CLI を設定する。

  • Manage Jenkins > Configure Global Security > SSH Server で適当に設定する。例: 8081
  • (User) > Configure > SSH Public keys に公開鍵を入れる。

    ssh localhost -p 8081 help
    ssh localhost -p 8081 build example-pipeline -f -v

これでコマンドラインからビルド出来る。

参考

Pipeline を調べる。

Pipeline はただの設定ファイルではなく Groovy ファイルという事だった。ということは pipeline, agent, stage と言った識別子は Groovy オブジェクトなはずだ。調べてみた。

println "pipeline: $pipeline"

pipeline {
    // println "agent: $agent"
    agent any 
    stages {
        // println "stages: $stages"
        stage('Stage 1') {
            steps {
                println "steps: $steps"
            }
        }
    }
}
  • pipeline 宣言の外側に println を書く事が出来た。pipeline はオブジェクトだった。
  • pipeline 宣言のすぐ内側には println を書くことが出来なかった。
  • stages 宣言のすぐ内側には println を書くことが出来なかった。
  • stage 宣言のすぐ内側には println を書くことが出来た。steps はオブジェクトだった。

実行結果

$ ssh localhost -p 8081 build example-pipeline -f -v
Started example-pipeline #15
Started from command line by tyamamiya
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] echo
pipeline: org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter@1a666b03
[Pipeline] node
Running on Jenkins in /Users/tyamamiya/.jenkins/workspace/example-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Stage 1)
[Pipeline] echo
steps: org.jenkinsci.plugins.workflow.cps.DSL@717597ff
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Completed example-pipeline #15 : SUCCESS

宿題

特殊構文: http://groovy-lang.org/dsls.html によると、pipeline {...} のような構文は pipeline({...}) のような関数呼び出しの省略形だという事だった。中括弧はクロージャを表すので agentstages も関数だと思ったのだが println 出来なかった。そもそも println を探せないというエラーが出る。

WorkflowScript: 4: Undefined section "println" @ line 4, column 5.
       println "agent: $agent"

普通クロージャというと外の環境を取り込む物だが、Groovy の場合もっと複雑な事が出来るらしい。agentstages が Groovy 的にどう解釈されるのか知りたい。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2