8000 How to switch between SSH keys? · Issue #540 · ruby-git/ruby-git · GitHub
[go: up one dir, main page]

Skip to content
How to switch between SSH keys? #540
Open
@ChristofferJoergensen

Description

@ChristofferJoergensen

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0