How To Mask An SSH Private Key in GitLab CI
Are you interested in how to mask an SSH Private Key inside the GitLab CI? In this short guide, we will first have a look at the problem, then think of how to solve it, and lastly, execute the solution!
- The Problem
- The Idea
- The Solution: Mask an SSH Private Key in the GitLab CI
When we want to create an SSH Private Key as a Variable inside GitLab, we get the following message that we cannot mask it:
The reason for that is that a variable has to follow these constraints (GitLab docu):
- All content is in a single line.
- Needs to be 8 characters or more and consist of only:
- Characters from the Base64 alphabet (RFC4648).
Therefore the newline (\n), =, -, etc. characters are problematic, and we somehow have to get rid of them.
Need help or want to share feedback? Join my discord community!
The problem is we cannot just delete them because if we did that, we would change the value of the key. The idea now is to encode the private key as a base64 string and then later decode it back to the original value. The reason for encoding it to base64 is that one of the constraints is that the content in the variable should only consist of base64 characters.
The Solution: Mask an SSH Private Key in the GitLab CI
To encode and decode the private key, we need to follow these steps:
- Create a new private key or use an existing one:
ssh-keygen -t rsa -b 4096
- Encode the private key and copy it to your clipboard:
$(cat .ssh/privatekey | base64 -w0)
- Paste into the content field of the GitLab Variable called
- Decode it inside a pipeline:
echo "$SSH_PRIVATE_KEY" | base64 -d > ~/.ssh/id_rsa
In this post, you learned how to create a maskable SSH Private Key inside GitLab CI with three simple steps:
- Encode Private Key to base64
- Store the base64 value inside a variable
- Decode the variable inside a pipeline
I hope that this short guide solved your problems. In case you liked it consider subscribing to my newsletter to get monthly updates on my content!
If this guide is helpful to you and you like what I do, please support me with a coffee!