Linux – ssh command to add a public key to the local `authorized_keys`

cheflinuxsshunix

Is there a single line command to tell SSH to add a provided public key to the local machine's authorized_keys file? A local version of ssh-copy-id?

I am writing a chef recipe and want to ensure a specific ssh public key is set for a certain user. I could overwrite the ~/.ssh/authorized_keys file each time, or attempt to some hacky way to add the line, but if there's an official command, it'll be more robust and prevent duplication.

Something like:

ssh-add-local-key "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDeblahdeblah user@somwhere"

For apt systems like Ubuntu or Debian there is an apt-add-repository command, so I wonder if there's a SSH equivalent.

I know I could use "echo blah >> authorized_keys", but I want something idempotent, which I can run regularly. With >> the file will grow in size every time.

Best Answer

I'm not aware of such a local command. I don't like ssh-copy-id foo@localhost (because it opens a SSH connection) and I even less like the error prone echo foo >> ~/.ssh/authorized_keys.

But since you're using chef, why don't you use the chef tools (mainly ruby) you have available?

For example:

ruby_block "authorized_keys" do
  block do
    file = Chef::Util::FileEdit.new("/home/#{username}/.ssh/authorized_keys")
    file.insert_line_if_no_match("/#{authorized_key}/", "#{authorized_key}")
    file.write_file
  end
end

insert_line_if_no_match documentation:

#insert_line_if_no_match(regex, newline) ⇒ Object

search the file line by line and match each line with the given regex if not matched, insert newline at the end of the file

This doesn't seem hacky all that much to me and provides an easy to understand way to solve your problem.

Another alternative would be Bill Warners answer to a similar question: https://stackoverflow.com/a/28283354/2376817

Related Topic