🔑

JenkinsのJob DSLでcredentialsを利用してGitHubからコンテンツを取得する

2025/01/20に公開

Jenkinsでseed jobを作っていて、credentialsが使いたいケースがあった。

シーンとしては、seed jobでジョブを作る過程で別のGitHubにあるリポジトリから、ジョブの設定ファイルを取得したいようなとき。
しかもGitHubに対してGitHub AppsでJenkinsからアクセスしていて、JenkinsのcredentialsにAppsは設定してある。
正直設計がイマイチだと思うが、変えられない前提だったので、そこは不問で。

解決方法は2種類。

Credentials Binding Pluginを利用して実現する

Credentials Binding Pluginで "秘密テキストや秘密ファイルを使用する" を使って "ユーザー名とパスワード(分離)" し、パスワードを GITHUB_TOKEN に入るようにすると、以下のコードで取得できるようになる。

def token = binding.GITHUB_TOKEN

def rawUrl = "https://raw.githubusercontent.com/organization/repository/branch/path/to/file" // organization, repository, branch, pathはそれぞれの文脈で
def config = new URL(rawUrl).getText(requestProperties: [
  "Authorization": "token ${token}"
])
println(config)

credentialsを引っ張り出して実現する

import jenkins.model.Jenkins

def credentials = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getCredentials().find { it.id == "hoge-credential" }
def token = credentials.getPassword()

def rawUrl = "https://raw.githubusercontent.com/organization/repository/branch/path/to/file" // organization, repository, branch, pathはそれぞれの文脈で
def config = new URL(rawUrl).getText(requestProperties: [
  "Authorization": "token ${token}"
])
println(config)

Multiple SCMが入っていなかったので、複数リポジトリをcloneしてハンドリングすることもできず、Job DSLだと直接 credentials も使えず、少々難儀した。

参考URL

Discussion