-bohrw
Last Updated: February 25, 2016
·
6.146K
· atomic-penguin

Generate SSH deploy keys with Chef and sshkey gem.

Don't ship SSH private keys to nodes with Chef, generate them programmatically with Chef and ship the public key to Chef Server, so it can be searched.

For Github/Gitlab/Bitbucket keys, maybe Cassiano Leal's deploy_keys cookbook will suit your needs.

Here is how I generate and ship a public deploy_key to another server with Chef.

# Install sshkey gem into chef
chef_gem 'sshkey'

# Base location of ssh key
pkey = node['jenkins']['master']['home'] + '/.ssh/id_rsa'

# Generate a keypair with Ruby
require 'sshkey'
sshkey = SSHKey.generate(
  type: 'RSA',
  comment: "#{node['jenkins']['master']['user']}@#{node['jenkins']['master']['host']}"
)

# Create ~/.ssh directory
directory "#{node['jenkins']['master']['home']}/.ssh" do
  owner node['jenkins']['master']['user']
  group node['jenkins']['master']['group']
  mode 00700
end

# Store private key on disk
template pkey do
  owner node['jenkins']['master']['user']
  group node['jenkins']['master']['group']
  variables(ssh_private_key: sshkey.private_key)
  mode 00600
  action :create_if_missing
end

# Store public key on disk
template "#{pkey}.pub" do
  owner node['jenkins']['master']['user']
  group node['jenkins']['master']['group']
  variables(ssh_public_key: sshkey.ssh_public_key)
  mode 00644
  action :create_if_missing
end

# Save public key to chef-server as jenkins_pubkey 
ruby_block 'node-save-pubkey' do
  block do
    node.set_unless['jenkins_pubkey'] = File.read("#{pkey}.pub")
    node.save unless Chef::Config['solo']
end

1 Response
Add your response

18726

ruby block haven't end.

over 1 year ago ·
Filed Under