How To Mask An SSH Private Key in GitLab CI

No Comments
Published: 27.11.2022

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!

  1. The Problem
  2. The Idea
  3. The Solution: Mask an SSH Private Key in the GitLab CI

The Problem

When we want to create an SSH Private Key as a Variable inside GitLab, we get the following message that we cannot mask it:

mask ssh private key in gitlab ci: problem

The reason for that is that a variable has to follow these constraints (GitLab docu):

Therefore the newline (\n), =, -, etc. characters are problematic, and we somehow have to get rid of them.

The Idea

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:

Need help or want to share feedback? Join my discord community!

  1. Create a new private key or use an existing one:
    ssh-keygen -t rsa -b 4096
  2. Encode the private key and copy it to your clipboard:
    $(cat .ssh/privatekey | base64 -w0)
  3. Paste into the content field of the GitLab Variable called SSH_PRIVATE_KEY:
    mask ssh private key in gitlab ci: solved
  4. Decode it inside a pipeline:
    echo "$SSH_PRIVATE_KEY" | base64 -d > ~/.ssh/id_rsa

Conclusion

In this post, you learned how to create a maskable SSH Private Key inside GitLab CI with three simple steps:

  1. Encode Private Key to base64
  2. Store the base64 value inside a variable
  3. 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!

KOFI Logo

If this guide is helpful to you and you like what I do, please support me with a coffee!

Helpful Links

Discussion (0)

Add Comment

Your email address will not be published. Required fields are marked *