尝试通过 gitlab-runner 在 Linux 服务器上执行 shell 脚本

问题描述 投票:0回答:1

我一直在尝试在 GitLab 中设置一个 CI 管道,每当功能分支与主分支合并时,它将执行

auto_update_test.sh
文件。我已经在我的 Linux 服务器上安装了
gitlab-runner
并使用项目运行程序注册了它。

我服务器上的 GitLab 存储库位于

/opt/splunktest
下。
auto_update_test.sh
的内容如下:

#!/bin/bash
Path to your Splunk app directory
APP_DIR="/opt/splunktest"
#Git pull in the dev branch
cd "$APP_DIR" || exit
cd /opt/splunktest
git pull origin main

以下是.gitlab-ci.yml的内容

# .gitlab-ci.yml
stages:
  - deploy
deploy:
 stage: deploy
 script:
   - ./auto_update_test.sh
only:
 - main

当我将功能分支(比如说“dev”分支)合并到 GitLab 中的主分支时,我希望在我的服务器上执行

auto_update_test.sh

当我在 dev 分支的

splunktext.txt
上推送文本更改并将 dev 合并到 main 时,它会显示“没有这样的文件或目录”错误:

gitlab build error

我已尝试检查所有权限。该存储库被设置为 splunk 用户,并且还将 gitlab-runner 用户添加到 splunk 组。

$ getent group splunk
splunk:x:2003:gitlab-runner

我已经添加了所有权限,auto_update_test.sh具有可执行权限。

重新启动 splunk 和 gitlab-runner 用户

linux gitlab-ci
1个回答
0
投票

值得检查:

GitLab CI/CD 管道:通过 SSH 运行脚本到远程服务器

多行 ssh 命令的更好方法

TL;博士

  1. 创建 SSH 密钥。 您将获得 2 个密钥:一把 私钥(例如:id_ed25519)和一把 公钥(例如:id_ed25519.pub)

  2. 添加私钥作为GitLab变量: 设置 -> CI/CD -> 变量 -> 展开 -> 添加变量 (GitLab 的变量是一个键值对。将 key 命名为 SSH_PRIVATE_KEY 并将您的 private-key 粘贴到 value 字段中。然后单击“添加变量”。)

  3. 再添加一个 Gitlab 变量:DServerIP 作为远程服务器的 IP 地址(在您的情况下,是托管 gitLab-runner 的服务器)

  4. public-key添加到远程服务器的.ssh文件夹下(应该是/home/username/.ssh或/root/.ssh)

  5. public-key粘贴到authorized_keys文件中(它应该是/home/username/.ssh/authorized_keys或/root/.ssh/authorized_keys,但如果您没有authorized_keys文件,请创建它。)

  6. 在 .gitlab-ci 文件中使用以下脚本

image: alpine:latest

stages:
  - Execute_script_on_remote_host

update:
  stage: Execute_script_on_remote_host
  before_script:
    - 'command -v ssh-agent >/dev/null || ( apk add --update openssh-client )'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $DServerIP >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
  script:
    - scp  ./auto_update_test.sh root@$DServerIP:/opt/splunktest
    - |
      ssh  -tt root@$DServerURL /bin/bash -s << EOT
      cd /opt/splunktest
      chmod +x auto_update_test.sh
      bash auto_update_test.sh
      exit
      EOT

备注:

  • 确保文件 auto_update_test.sh 与 .gitlab-ci.yml 位于同一目录中(或者只是更改其在脚本中的路径)
  • 您可以将所有命令放入项目中的 shell 脚本(例如:remote_update.sh)中并更改 SSH 命令:

remote_update.sh:

cd /opt/splunktest
chmod +x auto_update_test.sh
bash auto_update_test.sh
exit

脚本中的SSH命令:

script:
    - scp  ./auto_update_test.sh root@$DServerIP:/opt/splunktest
    - ssh  -tt root@$DServerIP "/bin/bash -s" <remote_update.sh

另请参阅:

© www.soinside.com 2019 - 2024. All rights reserved.