Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an ssh key using Chef

I would like to add a private SSH key to a machine using Chef.

I'm new to Chef, and not a ruby programmer so the code below might be less-than optimum

My recipe includes the following:

execute "add private ssh key" do
  command 'ssh-add ' + ::File.join('/home', node['user'], '.ssh/keys/id_rsa')
  user node['user']
end

and upon running sudo chef-client on the target machine, then we get "Could not open a connection to your authentication agent" when attempting to add the SSH key.

This indicates the ssh client is not running, so I change the recipe to start with eval $(ssh-agent) && in order to start the client. After this upon running sudo chef-client in the shell we see the command in green, indicating the command was executed successfully.

However, the id_rsa key has not been added for the logged in user, and I see the SSH client is not running.

I probably am barking up the wrong tee, but this suggests to me that the key was added for a different user - maybe side affect of Chef being ran with sudo (Chef does not work when sudo is not used).

Has anyone experience with working around this problem, or adding SSH keys to machines using Chef?

like image 492
Django Doctor Avatar asked Jan 01 '26 02:01

Django Doctor


1 Answers

Not sure from your question what you are looking for. The ssh-add should be used to load up the agent on a users host so the private keys can be forwarded through from host to host. This should be done with a login script such as .bashrc on the users client.

Sorry if I'm mistaking but I think you more than likely want to add a public key to the authorized_keys file for users on servers so they can be authenticated by a private key. To do this you can append the line in an execute resource:

execute "add pub key" do
  command "echo #{node['pub_key']} >> ~#{node['ssh_user']}/.ssh/authorized_keys"
  not_if "grep #{node['pub_key']} ~#{node['ssh_user']}/.ssh/authorized_keys"
end

A slightly better way would be to use the line cookbook which gives you an insert_if_no_match resource.

Probably the best way would be to use the users community cookbook which can install public keys from data_bags.

like image 142
Bill Warner Avatar answered Jan 02 '26 19:01

Bill Warner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!