Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to switch between SSH keys? #540

Open
ChristofferJoergensen opened this issue Dec 12, 2021 · 0 comments
Open

How to switch between SSH keys? #540

ChristofferJoergensen opened this issue Dec 12, 2021 · 0 comments

Comments

@ChristofferJoergensen
Copy link

I have created a bounty on Stackoverflow for an answer to this question.

Is there any way to set different SSH keys to ruby-git configuration on the fly, so I can work with different private repos?

What I've done is working well, but it works with one SSH key only.

I have created /ruby_git.sh in the root folder of my Rails app:

#!/bin/bash
exec /usr/bin/ssh -o StrictHostKeyChecking=no -i ./certs/private_key "$@"

I have created /certs/private_key with my SSH key:

-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----

I have created /initializers/git_init.rb:

Git.configure do |config|
  config.git_ssh = Rails.root.join("ruby_git.sh").to_s
end

I have also tried another approach, to create custom sh scripts and SSH private key files for each repo in runtime and delete them after use. But this seems to alter Git globally, so the next thread/session inherits the new Git config:

# @repo_id, @ssh_url and @private_key are instance variables set
# based on the repo that we try to interact with

cert_path   = Rails.root.join("git_config", "certs", @repo_id).to_s
config_path = Rails.root.join("git_config", "configs", "#{@repo_id}.sh").to_s
git_config  = "#!\/bin\/bash\n\nexec \/usr\/bin\/ssh -o StrictHostKeyChecking=no -i #{cert_path} \"$@\""

File.open(config_path, "w") { |f|
  f.write(git_config)
}

File.open(cert_path, "w") { |f|
  f.write(@private_key)
}

File.chmod(0755, config_path)
File.chmod(0600, cert_path)

Git.init

Git.configure { |config|
  config.git_ssh = config_path
}

Git.ls_remote(@ssh_url)

FileUtils.remove_entry(cert_path)
FileUtils.remove_entry(config_path)

Your environment

  • version of git and ruby-git: 1.8.1
  • version of ruby: ruby 3.0.0p0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant