CircleCIのGitHub連携でPermission denied (publickey)が起きたときの対処

CircleCI を使った GitHub リポジトリの CI で、ある日突然以下のようなエラーが起きるようになりました。

現象

CircleCI のログを見たところ、GitHub からソースコードをチェックアウトする際に、以下のようなエラーになっていました。

if [ "$existing_repo" = 'true' ] || [ 'false' = 'true' ]; then
  echo 'Fetching from remote repository'
  if [ -n "$CIRCLE_TAG" ]; then
    git fetch --force --tags origin
  else
    git fetch --force origin +refs/heads/master:refs/remotes/origin/master
  fi
fi

if [ -n "$CIRCLE_TAG" ]; then
  echo 'Checking out tag'
  git checkout --force "$CIRCLE_TAG"
  git reset --hard "$CIRCLE_SHA1"
else
  echo 'Checking out branch'
  git checkout --force -B "$CIRCLE_BRANCH" "$CIRCLE_SHA1"
  git --no-pager log --no-color -n 1 --format='HEAD is now at %h %s'
fi

Using SSH Config Dir '/home/circleci/.ssh'
git version 2.35.1
Cloning git repository
Cloning into '.'...
Warning: Permanently added the ECDSA host key for IP address '140.82.112.3' to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

exit status 128
CircleCI received exit code 128

https://app.circleci.com/pipelines/github/rubocop/rubocop-performance/811/workflows/536d4094-27ac-4714-9686-0c63887fdf50/jobs/5386

原因

GitHub 上の設定を見たところ、なぜか Deploy Keys が空になっていました。

対処方法

CircleCI 側のプロジェクト設定を「Project Settings」で開きます。

SSH Keys」を開いて、 (連携できていない) 既存の Deploy Key を削除します。

"Add Deploy Key" を押して SSH Key を追加します。

GitHub 側にも Deploy Keys への設定がされますので、ソースコードのチェックアウト可能になっていると思います。CircleCI のテストを Re-run してみましょう。

この問題が起きるようになった原因はわかりませんが、不特定のリポジトリで起きているようです。

現象に遭遇したとき参考までにどうぞ。