Managing multiple SSH keys for different Git services (like GitHub, Bitbucket, or GitLab) can sometimes get tricky. In this post, I’ll show you how to configure your SSH setup to automatically use the correct key when cloning from Bitbucket, without having to specify it every time.
Prerequisites
- You should already have an SSH key pair generated.
- Make sure your SSH public key is added to your Bitbucket account under Personal Settings > SSH Keys.
Step-by-Step Guide: Configuring SSH to Use a Specific Key for Bitbucket
When you have multiple SSH keys for different Git services or repositories, it’s a good idea to use the SSH config file to specify which key should be used for each service. This way, you can avoid conflicts and simplify your workflow.
1. Open the SSH Config File
SSH uses a configuration file located at ~/.ssh/config to define settings for each host (such as Bitbucket, GitHub, etc.). If the file doesn’t already exist, you can create it.
To open the SSH config file, run:
vim ~/.ssh/config
If the file doesn’t exist, it will be created when you save it.
2. Add Configuration for Bitbucket
Add a configuration section for Bitbucket to specify which SSH key to use when cloning or pushing to Bitbucket repositories.
Here’s what the configuration might look like:
Host bitbucket.org HostName bitbucket.org User git IdentityFile ~/.ssh/id_bitbucket_miguelnz
Here’s what each line does:
Host bitbucket.org: This tells SSH that this configuration applies when connecting to Bitbucket.
HostName bitbucket.org: The actual domain name for Bitbucket.
User git: The user to log in as when using SSH for Git operations.
IdentityFile ~/.ssh/id_bitbucket_miguelnz: This specifies the SSH private key file to use when connecting to Bitbucket.
Replace ~/.ssh/id_bitbucket_miguelnz with the actual path to your private SSH key for Bitbucket.
3. Save and Exit
Once you’ve added the configuration, save and exit the editor.
4. Set Correct File Permissions
SSH is very strict about file permissions for security reasons. If your SSH config or key files have improper permissions, SSH will refuse to use them. To fix this, run the following commands:
# Set correct permissions for the .ssh directory chmod 700 ~/.ssh # Set correct permissions for the private key file chmod 600 ~/.ssh/id_bitbucket_miguelnz # Set correct permissions for the config file chmod 600 ~/.ssh/config
This ensures that the .ssh directory and its contents are only accessible by you, which SSH requires for security reasons.
5. Clone the Repository
Now that you’ve configured SSH to use the correct key for Bitbucket, you can clone repositories without worrying about which SSH key is being used. Here’s how you can clone a repository from Bitbucket:
git clone [email protected]:yourusername/your-repo.git
The SSH client will automatically use the id_bitbucket_miguelnz key you specified in your config file whenever you interact with Bitbucket, making it easier to manage multiple keys.