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

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


本文结束。

相关推荐
你的人类朋友6 小时前
✨【GitLab】【CI/CD】核心概念一览
gitlab·自动化运维·devops
mCell7 小时前
Webhook:连接、自动化与系统集成的新范式
ci/cd·go·github
测试开发技术8 小时前
使用 Git 时出现 unable to access,如何解决?
git·面试题
zhougl9969 小时前
git项目,有idea文件夹,怎么去掉
java·git·intellij-idea
Gold Steps.15 小时前
基于 Gitlab、Jenkins与Jenkins分布式、SonarQube 、Nexus 的 CiCd 全流程打造
运维·ci/cd·gitlab·jenkins
tmacfrank17 小时前
Git 使用技巧与原理(一)—— 基础操作
git
dilvx17 小时前
git 配置 default editor
git
特种加菲猫21 小时前
构建完整工具链:GCC/G++ + Makefile + Git 自动化开发流程
linux·笔记·git·自动化
咚咚?1 天前
基于gitlab 构建CICD发布到K8S 平台
容器·kubernetes·gitlab
Franklin1 天前
VS 版本更新git安全保护问题的解决
git