Jenkins でローカルにあるレポジトリから github に同期したい。pipline で行う場合、 GitPublisher Plugin が使えないので、自分で git push する必要がある。
1. cred-id で github にアクセスするためのユーザー名とトークンを 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')
}
これで、 withCredentials で GIT_TOKEN にトークンが入り、 GIT_USERNAME にユーザー名が入る*1。
3. ローカルレポジトリに Jenkinsfile を push して、そのレポジトリから pipeline project を設定する。
ここで、Jenkins のプロジェクトの設定で Additional Behaviours -> Check out to specific local branch を加えて Branch name を ** または空欄にする必要がある。何故なら、初期状態ではワークスペース上の git はブランチから外れているからである*2。