LoginSignup
11
2

More than 3 years have passed since last update.

Jenkins Decrarative Pipelineで stage を配列定義

Posted at

複数環境を管理している場合などに、「全ての環境に対して処理を行いたい」という場合があります。

環境ごとに一つずつ処理を実行するのは面倒。
Pipelineでstageごとの処理を繰り返し書くのは面倒。
ループ処理で実施してしまいたいですよね。

やりたいこと

こんな処理です。
例として複数リージョンで処理をするケースをあげています。

pipeline {
    agent any
    stages{
        stage('ap-northeast-1') {
            steps{
                script{
                    echo "ap-northeast-1 の処理"
                }
            }
        }
        stage('us-east-1') {
            steps{
                script{
                    echo "us-east-1 の処理"
                }
            }
        }
    }
}

script の中身に、リージョン名だけ変えて何度も同じことを書くのは面倒だったりします。

配列のLoop

以下のように書くことで、変更する部分を変数化できます。

pipeline {
    agent any
    stages{
        stage('Prepare'){
            steps{
                script{
                    env_list = ["ap-northeast-1","us-east-1"]

                    env_list.each { region -> 
                        stage(region) {
                            echo "${region} の処理"
                        }
                    }
                }
            }
        }
    }
}

実行画面は以下のようになります。
image.png

Prepare Stageで、他のstageをラップしています。
これにより、配列を展開するGroovy処理を記述できるようになっています。

アレンジ版

map利用

map を利用することもできます。
stageごとに変動させたい値が2つある時便利です。

script{
    env_map = [
        "ap-northeast-1": "tokyo",
        "us-east-1": "virsinia"
    ]

    env_map.each { region -> 
        stage(region.key) {
            echo "${region.value} の処理"
        }
    }
}

実行画面は以下のようになります。
image.png

Parameters でパラメータ切り替え

stageに入る前に script を挟んでいることで、
if分岐などでStage内の内容を調整することも可能です。

pipeline {
  agent any
  parameters {
      choice(name: 'Cloud', choices: 'aws\ngcp', description: '説明')
  }
  stages{
    stage('Prepare'){
      steps{
        script{
          if (params.Cloud == 'aws'){
            env_map = [
              "tokyo": "ap-northeast-1",
              "virsinia": "us-east-1"
            ]                    
          } else if (params.Cloud == 'gcp'){
            env_map = [
              "tokyo": "asia-northeast1",
              "virsinia": "us-east4"
            ]
          }

          env_map.each { region -> 
            stage(region.key) {
              echo "${region.value} の処理"
            }
          }
        }
      }
    }
  }
}

最後に

Jenkins Decrarative Pipeline で stae を配列で定義する方法を紹介しました。
複数環境からの情報収集、複数環境へのデプロイなどで活用していけると思います。

確認には、Jenkins は 2.183, プラグインは初回起動時の推奨のもののみを使いました。

11
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
11
2