Unyablog.

のにれんのブログ

Jenkins でローカルレポジトリを github のレポジトリに同期する

Jenkins でローカルにあるレポジトリから github に同期したい。pipline で行う場合、 GitPublisher Plugin が使えないので、自分で git push する必要がある。

1. cred-idgithub にアクセスするためのユーザー名とトークンを Jenkins の credential に登録する。
2. Declarative pipeline で以下のスクリプトを書く。
withCredentials(
        [usernamePassword(
            credentialsId: 'cred-id',
            passwordVariable: 'GIT_TOKEN',
            usernameVariable: 'GIT_USERNAME'
            )]
        ) {
    sh('git push https://${GIT_USERNAME}:${GIT_TOKEN}@github.com/foo/bar master')
}

これで、 withCredentialsGIT_TOKENトークンが入り、 GIT_USERNAME にユーザー名が入る*1

3. ローカルレポジトリに Jenkinsfile を push して、そのレポジトリから pipeline project を設定する。

ここで、Jenkins のプロジェクトの設定で Additional Behaviours -> Check out to specific local branch を加えて Branch name を ** または空欄にする必要がある。何故なら、初期状態ではワークスペース上の git はブランチから外れているからである*2

参考

[JENKINS-28335] Step to run Git commands w/ credentials & tool (was: GitPublisher support) - Jenkins JIRA

*1:変数部はコンソールでは ** と表示される

*2:pipeline 上で checkout しても良い