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

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


本文结束。

相关推荐
拾-光3 小时前
【Git】命令大全:从入门到高手,100 个最常用命令速查(2026 版)
java·大数据·人工智能·git·python·elasticsearch·设计模式
Snooker_1467 小时前
TRAE、VSCode上进行git管理
ide·git·vscode
pzx_0019 小时前
【论文阅读】SWE-CI: Evaluating Agent Capabilities in Maintaining Codebases via Continuous Integration
论文阅读·人工智能·深度学习·神经网络·ci/cd
zincsweet9 小时前
Git开发工具教程
git
yuyuyui9 小时前
Git实战覆盖98%日常开发场景
git
Eloudy12 小时前
git clone --mirror 同步桥
大数据·git
cxwl3sxl12 小时前
重装系统后GIT仓库修复
git
OYangxf12 小时前
Git速查命令
大数据·git·elasticsearch
OYangxf12 小时前
Git Common Errors
大数据·git·elasticsearch
Mike_66612 小时前
git@gitlab-rdc.xxxxx.com: Permission denied (publickey).fatal: 无法读取远程仓库。
git·elasticsearch·gitlab