Reputation: 530
I am building a CI/CD for my django project using GitLab. As part of my deploy stage, I have
deploy:
stage: deploy
script:
- mkdir -p ~/.ssh
- echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
- cat ~/.ssh/id_rsa
- chmod 700 ~/.ssh/id_rsa
- eval "$(ssh-agent -s)"
- ssh-add ~/.ssh/id_rsa
- ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts
- chmod +x ./deploy.sh
- scp -o StrictHostKeyChecking=no -r ./.env ./docker-compose.prod.yml ec2-user@$EC2_PUBLIC_IP_ADDRESS:/home/ec2-user/app
- bash ./deploy.sh
only:
- master
The build breaks down at ssh-add ~/.ssh/id_rsa
with the error message Error loading key "/root/.ssh/id_rsa": invalid format
.
I have checked people with questions with similar error messages and none seem related to what I am doing.
Upvotes: 5
Views: 13494
Reputation: 530
I managed to fix it with the help of guys from the ##aws irc channel
The Problem
I generated a PKCS#1 key format instead of a PKCS#8 format. The PKCS#1 is represented as:
-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----
The PKCS#8 is represented as:
-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----
Solution
I simply copied the PRIVATE KEY and converted it here https://decoder.link/rsa_converter
You can also see a better elucidation here Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY"
Edited As indicated below, it is not a good idea to use websites to do the conversion. Especially when your private key is likely being sent to their servers. Instead, do the conversion locally as indicated here by @csgeek
Upvotes: 2
Reputation: 2531
I faced such issue, the error was "Error loading key "/root/.ssh/id_rsa": invalid format" It was due to protected variable, that only applied on protected branch. I mean to say if you use protected variable on unprotected branch it will not recognize the variable thus failed to recognize it.
Upvotes: 3