Skip to content

Encrypting secret files and use in jenkins

veeramarni edited this page Jun 7, 2020 · 13 revisions

Encrypting secret files and use in jenkins

This document explains how to encrypt files in a repo using gpg keys and giving jenkins access to these files

1- In jenkins instance install git-crypt and gnupg2

$ kubectl exec -it <JENKINS_POD> bash -n <NAMESPACE>
# apt-get install gnupg2
# apt-get install git-crypt

2- Make new directory to add gpg keys

# cd /var/jenkins_home
# mkdir keys

3- In your local machine generate gpg key pair for jenkins with no passphrase (if it's new instance other wise skip this step and use the existing one) gpg --gen-key

add the name and email 'jenkins' and 'jenkins@cdebase.com' (please note that this key is already created this is just an example)

4- Export the public and prive keys for jenkins user

$ gpg --list-keys
$ gpg --export -a jenkins > public.key
$ gpg --export-secret-key -a jenkins > private.key

5- Copy the exported keys to jenkins pod in the directory /keys

$ kubectl cp public.key <JENKINS_POD>:/var/jenkins_home/keys -n <NAMESPACE>
$ kubectl cp private.key <JENKINS_POD>:/var/jenkins_home/keys -n <NAMESPACE>

6- Import the keys in jenkins instance

$ kubectl exec -it <JENKINS_POD> bash -n <NAMESPACE>
# cd /var/jenkins_home/keys 
# gpg --import public.key
# gpg --allow-secret-key-import --import private.key
# gpg --list-keys

7- Set the trust of the key

# gpg --edit-key jenkins
> trust
> 5
> y
> quit

8- Start encrypting files in a repo and use git-crypt

$ cd repo
$ git-crypt init
$ touch .gitattributes

edit the file .gitattributes and add the following line to it <SECRET_FILE_DIRECTORY> filter=git-crypt diff=git-crypt save and exit
9- Add users to the repo

$ cd repo
$ git-crypt add-gpg-user --trusted jenkins

Note: if you need to add a different user export the public key, trust it then do step 9

10- Commit and push to you branch

Adding user key to a repo

  1. Add public key to gpg if it is not added yet otherwise skip to step 2.
$ gpg --import public.key
$ gpg --edit-key user@email.com

at editing key set trust to 5

> trust
> 5
> y
> quit
  1. Add the gpg user to git-crypt.
$ cd repo
$ git-crypt add-gpg-user --trusted user@email.com
$ git push