SSH to EC2 instance through Gitlab CICD and run commands

Problem to solve:
I am currently using gitlab CICD to ssh to one of our running Gitlab EC2 instance to run rake commands. I have the following code for testing purpose and It seems that while the SSH connection is established successfully, subsequent commands such as pwd and ls -l /etc/gitlab are not being executed. This issue causes the pipeline to hang without completing the execution of the desired commands.

image: buildtime_base_v2:3.25.1

stages:

  - test

test:

  stage: test

  script:

    - |

      echo "$SSH_KEY_VARIABLE" > ssh_key.pem

      chmod 600 ssh_key.pem

      ssh -i "ssh_key.pem" -t -t -o StrictHostKeyChecking=no centos@<ip>

      pwd

      ls -l /etc/gitlab

Hi,

You have to put all your commands as part of your ssh command. E.g.

ssh -i "ssh_key.pem" -t -t -o StrictHostKeyChecking=no centos@<ip> "pwd && ls -l /etc/gitlab"

(a side hint) there is no need for you to separate your commands like that with “|”. You can just do:

test:
  stage: test
  script:
      - echo "$SSH_KEY_VARIABLE" > ssh_key.pem
      - chmod 600 ssh_key.pem
      - ssh -i "ssh_key.pem" -t -t -o StrictHostKeyChecking=no centos@<ip> "pwd && ls -la /etc/gitlab"

Hope this helps!