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

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


本文结束。

相关推荐
苍墨穹天2 小时前
git 介绍+常用命令
git
1024小神2 小时前
git push出错Push cannot contain secrets
git
世俗ˊ6 小时前
浅显易懂的Git教程
git
CyreneSimon11 小时前
git push : RPC failed; HTTP 400 curl 22 The requested URL returned error: 400
git·http·rpc
MAMA668111 小时前
Git切换分支
git
橘子真甜~13 小时前
Linux基础3-基础工具4(git),冯诺依曼计算机体系结构
linux·运维·服务器·开发语言·git
MAMA66811 天前
更新 Git 软件
git
ByteSaid1 天前
Android 内核开发之—— repo 使用教程
android·git
CrazyCosin1 天前
git分支管理的一些常用规范
git