Gitlab runner 実行時の Host key verification failed. エラーの解決方法

一、障害の症状

私の.gitlab-ci.ymlファイルは以下のとおりです:

before_script:
  - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
  - eval $(ssh-agent -s)
  - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh

master-deploy:
  stage: deploy
  only:
    - master
  script:
    - scp -r index.html user@url:/index.html

出力されたエラーは以下のとおりです:

Host key verification failed.
lost connection
Cleaning up project directory and file based variables
00:00
+ set -o
+ grep pipefail
+ set -o pipefail
+ set -o errexit
+ set +o noclobber
+ :
···
+ exit 0
ERROR: Job failed: exit status 1

秘密鍵はローカルでのテストでは正常に動作しました。

二、原因

本番サーバーへの初めての接続であるため、ssh が以下の確認を返し、実行が中断されてしまいます

The authenticity of host 'xxx' can't be established.
ESDSA key fingerprint is xxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no)?

三、解決方法

  1. .gitlab-ci.ymlファイルに以下のコードを追加すれば実行できます:
before_script:
  - ssh-keyscan [you_host_url] >> ~/.ssh/known_hosts
  - chmod 644 ~/.ssh/known_hosts