.gitlab-ci.yml 中描述 SSH 命令最清晰、简洁的方式

Fin*_*sse 4 linux ssh shell continuous-deployment gitlab-ci

.gitlab-ci.yml通常我会通过 SSH 在远程服务器上执行以下命令:

# The job
deploy:
  script:
    # I've omitted the SSH setup here
    - |
      ssh gitlab@example.com "
        # Makes the server print the executed commands to stdout. Otherwise only the command output is printed. Required for monitoring and debug.
        set -x &&

        # Executes some commands
        cd /var/www/example &&
        command1 &&
        command2 &&
        command3 &&
        command4 &&
        command5
      "
Run Code Online (Sandbox Code Playgroud)

它工作正常,但 YAML 代码看起来太复杂:

  • set -x命令更像是一个样板文件,而不是有用的代码。普通 CI 命令不需要它,因为 GitLab CI 会自动打印它们。
  • &&每行都有样板。当其中一个命令失败时,它们会使执行停止。否则,当一个命令失败时,将执行下一个命令(与普通作业命令相反)。
  • 所有 SSH 命令都是单个 YAML 字符串,因此编辑器不会突出显示注释和命令,因此代码难以阅读。

有没有一种更清晰、更方便的方法通过 SSH 在远程计算机上执行多个命令,而没有上述缺点?

我不想使用 Ansible 等外部部署工具来保持 CD 配置尽可能简单(欢迎使用默认的 POSIX/Linux 命令)。我还考虑过在单独的ssh调用中运行每个命令,但我担心由于建立了多个 SSH 连接,它可能会增加作业执行时间(但我不确定):

deploy:
  script:
    - ssh gitlab@example.com "cd /var/www/example"
    - ssh gitlab@example.com "command1"
    - ssh gitlab@example.com "command2"
    # ...
Run Code Online (Sandbox Code Playgroud)

Fin*_*sse 5

更简洁明了的方法是使用set -e. 当其中一个命令失败时,它会使整个脚本失败。它让你不必&&在每一行都使用:

# The job
deploy:
  script:
    # I've omitted the SSH setup here
    - |
      ssh gitlab@example.com "
        # Makes the server print the executed commands to stdout. Makes the execution stop when one of the commands fails.
        set -x -e

        # Executes some commands
        cd /var/www/example
        command1
        command2
        command3
        command4
        command5

        # Even complex commands
        if [ -f ./.env ]
          then command6
          else
            echo 'Environment is not set up'
            exit 1
        fi
      "
Run Code Online (Sandbox Code Playgroud)