gitlab 的CI/CD (二)

前言

上文完成了gitlab-runner的基础配置及将gitlab的制品上传至软件包库(产品库)的脚本编写;

本文实现gitlab的ci/cd对远程服务器的操作;

介绍

要让Gitlab Runner部署到远程机器,远程机器必须信任gitlab runner账户。

先执行

复制代码
su gitlab-runner

切换到gitlab-runner账户

a服务器 gitlab-runner所在服务器

b服务器 部署项目的远程服务器

免密通道建立

生成密钥

a服务器上执行

复制代码
ssh-keygen

或者

复制代码
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

执行后 /home/gitlab-runner/.ssh 目录下,

会新生成两个文件:id_rsa.pub和id_rsa

将a服务器公钥上传至b远程服务器的SSH(安全外壳协议)认证文件

复制代码
scp -r  /home/gitlab-runner/.ssh/id_rsa.pub root@b服务器的ip:/root/.ssh/authorized_keys

如果目标是追加公钥,可以使用 >> 操作符通过 SSH 连接来实现

复制代码
cat /home/gitlab-runner/.ssh/id_rsa.pub | ssh root@b服务器的ip 'cat >> /root/.ssh/authorized_keys'

这样可以避免权限和覆盖问题。

验证

复制代码
ssh root@b服务器的ip

.gitlab-ci.yml文件编写

着重查看ssh部分编写

复制代码
stages:
  - build
  - deploy
  - ssh

build:
  stage: build
  script:
    - echo "xxx"
  artifacts:
    paths:
      - "dist.tar.gz"
      - "update_description.txt"

deploy:
  stage: deploy
  needs:
    - build
  script:
    - echo "xxx"
  artifacts:
    paths:
      - "dist.tar.gz"
      - "update_description.txt"

ssh:
  stage: ssh
  needs:
    - deploy
  before_script:
    # 查找安装ssh-agent
    # - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - 'which ssh-agent || ( yum update -y && yum install openssh-client -y )'

    # 启动 ssh-agent
    - eval $(ssh-agent -s)

    # 将GitLab服务器私钥添加到ssh-agent代理中
    - chmod 400 ~/.ssh/id_rsa
    - ssh-add ~/.ssh/id_rsa

  script:
    - echo "传输到远程"
    - ssh root@b服务器的ip "mkdir -p /home/xxx/${CI_COMMIT_TAG:-latest}"
    - scp -r "dist.tar.gz" root@b服务器的ip:/home/xxx/${CI_COMMIT_TAG:-latest}/
    - scp -r "update_description.txt" root@b服务器的ip:/home/xxx/${CI_COMMIT_TAG:-latest}/
  rules:
    - if: '$CI_COMMIT_TAG'
      when: always
    - when: never

流水线执行完后,去远程服务器查看对应目录即可完成验证;


本文结束。

相关推荐
xixingzhe26 小时前
软件开发测试分层与CI/CD、沙箱使用完整指南
ci/cd·测试
小二·8 小时前
Next.js 15 企业级实战:从项目搭建到CI/CD全链路(App Router + Server Components + Turbopack)
javascript·ci/cd·turbopack
咋吃都不胖lyh11 小时前
提交(Commit)到本地的 Git 仓库,然后才能推送(Push)到远程的 Git 仓库
git
__zRainy__12 小时前
VS Code 自动同步如何重写 Git 历史:一次重复合并冲突的排查与恢复
git
IT码农-爱吃辣条13 小时前
AI Codeview 安装与使用教程
git·ai
司南-704914 小时前
怎么使用git打包tag,并推送到远程仓库
git
考虑考虑14 小时前
git中的tag
git·gitlab·github
REDcker15 小时前
Git浅克隆详解与实践
大数据·git
xexpertS15 小时前
CI/CD 流水线如何成为自动化发布负责人
ci/cd·自动化
养肥胖虎1 天前
Git提交规范笔记:feat和fix到底该怎么写
git·conventionalcommits