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 "[email protected]"

执行后 /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

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


本文结束。

相关推荐
zhang23839061541 小时前
IDEA add gitlab account 提示
java·gitlab·intellij-idea·idea
Э时间行者于我2 小时前
git同时删除多个分支
git
宁酱醇7 小时前
各种各样的bug合集
开发语言·笔记·python·gitlab·bug
我的golang之路果然有问题9 小时前
给git配置SSH(github,gitee)
经验分享·笔记·git·学习·gitee·ssh·github
漫步企鹅10 小时前
[Git] Git Stash 命令详解
git·git push·git pull·git commit·git pull rebase
船长@Quant12 小时前
协作开发攻略:Git全面使用指南 — 第二部分 高级技巧与最佳实践
git·版本控制·源代码管理·协作开发
用户126538387051214 小时前
github 和 gitee 配置问题及相关问题解决
git·github
极小狐15 小时前
极狐GitLab Git LFS 速率限制如何设置?
运维·git·ssh·gitlab·github
极小狐15 小时前
如何解决极狐GitLab 合并冲突?
人工智能·git·机器学习·gitlab
一袋米扛几楼9815 小时前
【GIT】github中的仓库如何删除?
git·github