These are the procedures that you need to do
On your local machine or EC2, generate a new SSH key:
ssh-keygen -t rsa -b 4096 -C "gitlab-runner" -f my_gitlab_runner_key
Copy the private key to GitLab:
Go to your GitLab repo > Settings > CI/CD > Variables, and add:
-
Key:
CI_SSH_PRIVATE_KEY
-
Value: Paste the contents of
my_gitlab_runner_key
-
Type: Variable
-
Mask: (recommended)
-
Protected: if used in protected branches only
Deploy the public key to the remote host
On the target server
stages:
- test
test-runner:
stage: test
tags:
- dev-pbr
script:
- echo " GitLab Runner tagged 'dev-pbr' is working!"
- echo "Running on $(uname -a)"
- python3 --version
- pip3 --version
# Create sample file
- echo "This is a test file created by GitLab CI/CD" > test_file.txt
- mkdir -p ~/.ssh
- echo "$CI_SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- ssh-keyscan -H 1.112.140.30 >> ~/.ssh/known_hosts 2>/dev/null
# Copy file to remote server
- echo "Copying file to remote server..."
- scp -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no test_file.txt $SSH_USER@1.112.140.30:/home/ubuntu/temp/
- echo " File copied successfully to remote server!"
How to test
Copying a test file from your CI/CD job to /home/ubuntu/temp on the remote server 1.112.140.30 ( IP ) using SSH is a perfect way to validate:
.gitlab-ci.yml
stages:
- test
test-runner:
stage: test
tags:
- dev-pbr
script:
- echo " GitLab Runner tagged 'dev-pbr' is working!"
- echo "Running on $(uname -a)"
- python3 --version
- pip3 --version
# Create sample file
- echo "This is a test file created by GitLab CI/CD" > test_file.txt
- mkdir -p ~/.ssh
- echo "$CI_SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- ssh-keyscan -H 1.112.140.30 >> ~/.ssh/known_hosts 2>/dev/null
# Copy file to remote server
- echo "Copying file to remote server..."
- scp -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no test_file.txt $SSH_USER@1.112.140.30:/home/ubuntu/temp/
- echo " File copied successfully to remote server!"