Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The most clear and concise way to describe SSH commands in .gitlab-ci.yml

Usually I make the following job in my .gitlab-ci.yml to execute commands on a remote server via SSH:

# The job
deploy:
  script:
    # I've omitted the SSH setup here
    - |
      ssh [email protected] "
        # 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
      "

It works correctly, but the YAML code looks too complicated:

  • The set -x command is more a boilerplate than a useful code. It's not required for ordinary CI commands because GitLab CI prints them automatically.
  • && on every line is boilerplate too. They make the execution stop when one of a commands fails. Otherwise the next commands will be executed when one fails (in contrast to ordinary job commands).
  • All the SSH commands are a single YAML string therefore editors don't highlight the comments and commands so the code is hard to read.

Is there a more clear and convenient way to execute multiple commands on a remote machine through SSH without the cons described above?

I'd like to not use external deployment tools like Ansible to keep the CD configuration as simple as possible (default POSIX/Linux commands are welcome). I'v also considered running each command in a separate ssh call but I'm afraid it may increase the job execution time because of multiple SSH connection establishments (but I'm not sure):

deploy:
  script:
    - ssh [email protected] "cd /var/www/example"
    - ssh [email protected] "command1"
    - ssh [email protected] "command2"
    # ...
like image 369
Finesse Avatar asked Oct 19 '25 22:10

Finesse


1 Answers

A more concise and clear way is to use set -e. It makes the whole script fail when one of the commands fails. It lets you not use && on every line:

# The job
deploy:
  script:
    # I've omitted the SSH setup here
    - |
      ssh [email protected] "
        # 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
      "
like image 129
Finesse Avatar answered Oct 22 '25 13:10

Finesse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!