sshgitlab-ci.ymldocker-run

.gitlab-ci.yml: Executing Multiple Commands on Remote Server via SSH


Given a .gitlab-ci.yml file in which it is needed to log in to a remote server via SSH and run there a list of commands. I tried using here-doc but without much luck. Based on my attempts to find the root of the problem, it looks like .gitlab-ci.yml doesn't accept here-doc. And it produced a bunch of errors.

Below is an excerpt:

deploy_to_server_job:
  stage: deploy_to_server
  tags:
    - server-runner
  image: ubuntu:22.04
  script:
    - chmod og= $ID_RSA
    - |
      ssh -tt -i $ID_RSA -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP bash << EOF
        docker system prune --force
        echo "Running container with image: $FULL_IMAGE_NAME"
        docker run -p 127.0.0.1:$SERVER_PORT:$SERVER_PORT \
        --env JWT_AUTH_SECRET=$JWT_AUTH_SECRET \
        --env JWT_AUTH_EXPIRES=$JWT_AUTH_EXPIRES \
        --env JWT_REFRESH_SECRET=$JWT_REFRESH_SECRET \
        --env JWT_REFRESH_EXPIRES=$JWT_REFRESH_EXPIRES \
        --env MONGODB_URI=$MONGODB_URI \
        --env PORT=$PORT \
        -d --name admin-server $FULL_IMAGE_NAME
        exit
      EOF

Then I rewrote an ssh command in one line:

    - ssh -tt -i $ID_RSA -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "whoami; echo Running container with image $FULL_IMAGE_NAME; docker system prune --force; docker run --name admin-server -d -p 127.0.0.1:$SERVER_PORT:$SERVER_PORT --env JWT_AUTH_SECRET=$JWT_AUTH_SECRET --env JWT_AUTH_EXPIRES=$JWT_AUTH_EXPIRES --env JWT_REFRESH_SECRET=$JWT_REFRESH_SECRET --env JWT_REFRESH_EXPIRES=$JWT_REFRESH_EXPIRES --env MONGODB_URI=$MONGODB_URI --env PORT=$PORT $FULL_IMAGE_NAME; exit"

All the error have gone except one:
bash: line 2: --env: command not found

I cannot figure out why the docker run --env flag is treated as a separate command. When changing all --env to -e, the error becomes bash: line 2: -e: command not found (so, it is that flag from docker run).

Question: In .gitlab-ci.yml, how to properly put commands that will run on a remote server?

Note: I've just started learning GitLab pipelines (I've thought I'd find a solution, but I've been struggling with this issue for a week), and maybe it's not only docker run that will throw such errors.


Solution

  • Jim's comment gave me an idea, and I managed to find the root of the problem: MONGODB_URI value should be quoted:

            --env MONGODB_URI="$MONGODB_URI" \