关于学习 Gitlab-runner 遇到的一些坑

Alpine 容器使用ssh连接部署服务器

job_name:
image: node:alpine
before_script:
- 'which ssh-agent || (apk update && apk add openssh-client)' # 如果找不到 ssh-agent,安装 ssh 服务
# run ssh-agent
- eval $(ssh-agent -s)
# add ssh key stored in SSH_PRIVATE_KEY variable to the agent store
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null # 讲 ssh-private-key 添加到 ssh-agent
- mkdir -p ~/.ssh
- ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts # 跳过询问是否添加 known_hosts 步骤
- chmod 644 ~/.ssh/known_hosts
script:
# 执行 ssh 或者其他命令

其他容器(基于Ubuntu)

job_name:
stage: deploy
only:
- main
before_script:
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
- eval $(ssh-agent -s) # 启动 ssh-agent
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null # 讲 ssh-private-key 添加到 ssh-agent
# or
- bash -c 'ssh-add <(echo "$SSH_PRIVATE_KEY")'
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts # 跳过询问是否添加 known_hosts 步骤
- chmod 644 ~/.ssh/known_hosts
script:
# 开始执行 ssh 或者其他操作