LoginSignup
14
2

More than 5 years have passed since last update.

Github Pull RequestをJenkins経由でテストを実行する場合にパラメータを設定する方法

Posted at

この記事は リクルートライフスタイル Advent Calendar 2016 の7日目の記事です。

はじめに

データ基盤Tの@byaです。
本記事は「Pull Requestの内容からパラメータを取得し、JenkinsでJobを実行する」について聞きます。

基本的にJenkinsのGithub Pull Request Builder Pluginを使えば、Githubの指定したリポジトリにPull Requestが作成されと、Jenkinsであらかじめ設定したJobが実行し、その実行結果をGithubに通知し、記録してくれます。つまり、このレポジトリにどのようなPull Requestきても、同じ「A」というjobが実行されます。しかし、業務上は「Pull Requestの内容に応じて、別々のjobを実行したい」という場合があると思います。その工夫について以下書きます。

準備

用意するものは、GithubリポジトリとJenkinsサーバーです。 設定や導入について以下の記事を参考してください。

パラメータを設定する

Pull Requestの内容によってJenkinsで実行されるjobが異なるので、それを識別させるにはPull Requestのdescription(説明)にパラメータを設定します。以下の画像は、"Job ID"にJenkinsのjobを指定する例です。

Screen Shot 2016-12-07 at 16.51.39.png

パラメータを取得する

上記のパラメータを取得するために以下のpythonを書きました。

# coding:utf-8
from fabric.api import local
import json


oauth_token = "githubの oauth token"
github_api_url = "githubのAPI URL"
owner = "レポジトリのオーナー名"
repo = "レポジトリ名"
git_current_commit_id = "コミットID"


def _search_pullreq_id(oauth_token, git_current_commit_id, pull_requests):

    for i in range(len(pull_requests)):
        pq_commits_raw = local('curl -H "Authorization: token {0}" {1}'.format(
            oauth_token, pull_requests[i]["commits_url"]), capture=True)
        pq_commits = json.loads(pq_commits_raw)

        for pqc in pq_commits:
            if git_current_commit_id == pqc['sha']:
                # Found
                return i

# Extract parent commit id
commit_raw = local('curl -H "Authorization: token {0}" {1}/repos/{2}/{3}/commits/{4}'.format(
    oauth_token, github_api_url, owner, repo, git_current_commit_id), capture=True)
git_current_commit_id = json.loads(str(commit_raw))['parents'][-1]['sha']

# Fetch all Pull Requests
pull_requests_raw = local('curl -H "Authorization: token {0}" {1}/repos/{2}/{3}/pulls'.format(
    oauth_token, github_api_url, owner, repo), capture=True)
pull_requests = json.loads(str(pull_requests_raw))

# Search current commit's pull request id
pull_request_id = _search_pullreq_id(oauth_token, git_current_commit_id, pull_requests)

# Extract current pull request's description
description = pull_requests[pull_request_id]['body']

# Extract jod id
job_id = description.split("Job ID:")[1].splitlines()[0].strip(":").strip().encode('utf-8')

ややハードコーディングになってしまいましたが、やっていることはPull Requestされたgithubの「commit id」から「pull request id」を特定し、その「pull request id」からの「説明文(body)」を抽出して、パラメータを取得しています。
ちなみにGithub Pull Request Builder Pluginを使うと、githubの「commit Id」しか分からないため、上記のように「pull request id」を取得するコードを自分で書かなければなりません。

まとめ

上記でやったことを図にまとめると:
Screen Shot 2016-12-07 at 18.24.51.png

14
2
1

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