SSH to EC2 instance through Gitlab CICD and run commands

25 Views Asked by At

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

1

There are 1 best solutions below

0
Jim Redmond On

This YAML isn't telling SSH to run any commands remotely; it's saying "SSH to the box, and then when you're done run these other commands locally". You'll need to put the remote-system commands into the SSH command: ssh -i /path/to/key <other options here> user@host "pwd && ls -l /etc/gitlab/". This will SSH to host using the specified parameters; run pwd on host; and then, if pwd exited successfully, run ls -l /etc/gitlab/ on host.

If the commands to run remotely become unwieldy, then put them in a script on the remote host: ssh -i /path/to/key <other options here> user@host "/opt/deployment_script.sh". This will SSH to host using the specified parameters, and then run /opt/deployment_script.sh on host.