Maven ビルドパイプラインでの Git メタデータ自動取得と利用方法

ビルドコンテキスト情報の追跡と実装

アプリケーションのデプロイ先で、実際にビルドされたソースコードの正確なバージョンやブランチ状況を確認することは、トラブルシューティングや監査において重要です。これを実現するための標準的なアプローチとして、Maven プラグインを使用した Git リポジトリ情報の抽出があります。

特定のプラガインを利用することで、ビルド時にリポジトリの状態を検出し、プロジェクトの属性ファイルに埋め込むことができます。これにより、ランタイム時にその情報をプログラム的に参照することが可能になります。

Maven プロジェクトへの統合設定

プロジェクトのルートディレクトリにあるビルド定義ファイルを変更し、必要なモジュールを登録します。


<build>
  <plugins>
    <plugin>
      <groupId>pl.project13.maven</groupId>
      <artifactId>git-commit-id-plugin</artifactId>
      <version>4.0.4</version>
      <executions>
        <execution>
          <id>get-the-git-infos</id>
          <goals>
            <goal>revision</goal>
          </goals>
          <phase>initialize</phase>
        </execution>
      </executions>
      <configuration>
        <verbose>true</verbose>
        <failOnNoGitDirectory>false</failOnNoGitDirectory>
        <format>json</format>
        <includeOnlyProperties>
          <includeOnlyProperty>^git.build.time$</includeOnlyProperty>
          <includeOnlyProperty>^git.commit.user.name$</includeOnlyProperty>
          <includeOnlyProperty>^git.branch$</includeOnlyProperty>
        </includeOnlyProperties>
        <offline>false</offline>
      </configuration>
    </plugin>
  </plugins>
</build>

生成されたメタデータファイルの確認

ビルドコマンドを実行すると、コンパイル後のディレクトリ内に JSON またはプロパティ形式の情報ファイルが出力されます。ここでは `git-info.json` として出力される例を示します。


{
  "git.branch": "develop-feature-v1",
  "git.commit.id": "9f8c2a1b3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a",
  "git.build.time": "2023-10-15T09:30:00+0900",
  "git.commit.user.name": "Developer Name",
  "shortCommitId": "9f8c2a1b"
}

アプリケーション内での情報利用

この生成されたファイルをクラスパスから読み込み、アプリケーションロジックで使用できます。ここでは静的ユーティリティクラスとして実装するサンプルを示しています。


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BuildContextProvider {

    private static final Logger logger = LoggerFactory.getLogger(BuildContextProvider.class);
    private static final String FILE_PATH = "/git-info.json";

    private static Properties buildMetadata;

    static {
        buildMetadata = new Properties();
        InputStream inputStream = BuildContextProvider.class.getResourceAsStream(FILE_PATH);
        if (inputStream != null) {
            try {
                // Note: In real scenario handling JSON may require Jackson/Gson, 
                // here we assume property mapping for demonstration compatibility
                // Simulating property load from the resource file content
                Properties temp = new Properties();
                temp.load(inputStream);
                // Transfer simplified properties here
                buildMetadata = temp; 
            } catch (IOException e) {
                logger.warn("Failed to load build metadata", e);
            } finally {
                try {
                    if (inputStream != null) inputStream.close();
                } catch (IOException ignored) {}
            }
        } else {
            logger.debug("Build metadata file not found in classpath");
        }
    }

    public static String getBranchName() {
        return safeGetValue("git.branch");
    }

    public static String getCommitHash() {
        return safeGetValue("git.commit.id");
    }

    public static String getTimestamp() {
        return safeGetValue("git.build.time");
    }

    private static String safeGetValue(String key) {
        String val = buildMetadata.getProperty(key);
        if (val == null || val.isEmpty()) {
            return "UNDEFINED";
        }
        return val;
    }
}

このように実装することで、稼働中のシステムログやヘルスチェックエンドポイントにおいて、現在のビルドソースの詳細を即座に提供することができます。

タグ: Maven git-commit-id-plugin Java Microservices build-metadata

8月3日 18:14 投稿