🐙

[GitHub Actions] コンテナ上でactions/checkoutを使った後にgit操作できない

2023/04/29に公開

コンテナ上でgit操作できない

GitHub Actions のジョブをコンテナ上で実行する際、actions/checkout 後にgit操作をすると以下のエラーが出てしまいます。

fatal: detected dubious ownership in repository at '/__w/github-actions-playground/github-actions-playground'
To add an exception for this directory, call:

	git config --global --add safe.directory /__w/github-actions-playground/github-actions-playground
Error: Process completed with exit code 128.

例えば、以下のようなワークフローを実行する場合です。

name: Minimal example
on: push
jobs:
  commit:
    runs-on: ubuntu-latest
    container: alpine/git:latest
    steps:
      - uses: actions/checkout@v3
      - name: Empty commit
        run: |
          git config --global user.email "test@example.com"
          git config --global user.name "test"
          git commit --allow-empty -m "test"

コンテナを使わずランナー上で直接実行する場合には、この問題は起きません。

safe.directory とは?

CVE-2022-24765という脆弱性に対応するためGit 2.35.2以降に入った機能です。このバージョン以降、Gitは実行ユーザーが所有権を持たない.gitディレクトリをデフォルトで読み込まないようになりました。この動作に例外を設けるのがsafe.directoryという設定項目です。

https://github.blog/2022-04-12-git-security-vulnerability-announced/

github.workspaceの不具合に注意

つまり、エラーメッセージのとおりsafe.directoryの設定をすれば良いわけです。ところが、以下のように書くとうまく動きません。

- name: Set up a Git safe directory
  run: git config --global --add safe.directory "${{ github.workspace }}"

これはコンテナ上でgithub.workspaceコンテキストが正しいワークスペースディレクトリの場所を示さないというGitHub Actionsの不具合によるものです。

https://github.com/actions/runner/issues/2058

GITHUB_WORKSPACE環境変数は正しく動作するので、そちらを利用しましょう。

- name: Set up a Git safe directory
  run: git config --global --add safe.directory "${GITHUB_WORKSPACE}"

結論

最初に示した例は、以下のように記述することでコンテナ上でも意図したとおりに動作します。

name: Minimal example
on: push
jobs:
  commit:
    runs-on: ubuntu-latest
    container: alpine/git:latest
    steps:
      - name: Set up a Git safe directory
        run: git config --global --add safe.directory "${GITHUB_WORKSPACE}"
      - uses: actions/checkout@v3
      - name: Empty commit
        run: |
          git config --global user.email "test@example.com"
          git config --global user.name "test"
          git commit --allow-empty -m "test"

Discussion