To access a Git repository Jenkins can use an SSH key.
To add the SSH key to the Jenkins server use the following Chef script
Store the SSH key in an encrypted data bag called “keys”.
{ "id": "ci_private_keys", "ci_github_key": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----", }
Add the following to the Jenkins Chef recipe
- Install Git
package 'git'
- Install the Git and Credentials Jenkins plugins
jenkins_plugin 'git' jenkins_plugin 'credentials'
- Copy the SSH key to the Jenkins server
rsa_key = data_bag_item('keys', 'ci_private_keys') file '/var/lib/jenkins/.ssh/id_rsa' do content "#{rsa_key['ci_github_key']}" owner 'jenkins' group 'jenkins' mode '0600' end
- Add github.com to the known hosts
bash 'provide github.com RSA fingerprint' do code <<-EOF ssh-keyscan github.com >> /var/lib/jenkins/.ssh/known_hosts chown jenkins.jenkins /var/lib/jenkins/.ssh/known_hosts EOF not_if{system('grep github.com /var/lib/jenkins/.ssh/known_hosts')} end
To specify the SSH key in the Git step
- When the Jenkins server is operational, navigate to the Web interface
- Create a new Jenkins project
- In the Source Code Management section
- Select Git
- Enter the SSH URL of the repository
- When you are adding the first project, click the Add button to create the credential
- Click Jenkins to select the credentials provider
- Select SSH Username with private key as the Kind
- Enter the username you used when you created the SSH key for the Git repository
- Select From the Jenkins master ~/.ssh as the Private Key
- Click the Add button
- Click Jenkins to select the credentials provider
- In the Credentials drop down select the credential you have created (the Git user name)