Configure GitLab with SSH Keys (Simple Setup)

Okay, here’s a comprehensive article on configuring GitLab with SSH keys, aiming for a simple setup and approximately 5000 words. I’ve structured it with clear headings, subheadings, and explanations to make it as accessible and informative as possible. This goes beyond a basic setup guide and includes troubleshooting, best practices, and explanations of underlying concepts.


Configure GitLab with SSH Keys (Simple Setup): A Comprehensive Guide

This guide provides a detailed walkthrough for setting up Secure Shell (SSH) keys with GitLab, enabling secure and convenient access to your repositories without constantly entering your password. While the process is straightforward, understanding the underlying concepts and potential issues is crucial for a smooth experience. This guide caters to both beginners and those seeking a deeper understanding of SSH key configuration with GitLab.

Table of Contents

  1. Introduction: Why Use SSH Keys with GitLab?

    • 1.1 The Problems with Password Authentication
    • 1.2 The Advantages of SSH Key Authentication
    • 1.3 Understanding the Concept of Public-Key Cryptography
    • 1.4 SSH and GitLab: How They Work Together
  2. Prerequisites

    • 2.1 A GitLab Account
    • 2.2 Git Installed on Your Local Machine
    • 2.3 An SSH Client (Usually Included with Git)
    • 2.4 Operating System Considerations (Windows, macOS, Linux)
  3. Generating Your SSH Key Pair

    • 3.1 Step-by-Step Key Generation (All Platforms)
      • 3.1.1 Opening Your Terminal or Command Prompt
      • 3.1.2 Using the ssh-keygen Command
      • 3.1.3 Choosing a Key Type (RSA, Ed25519)
      • 3.1.4 Specifying a File Location
      • 3.1.5 Setting a Passphrase (Recommended)
      • 3.1.6 Understanding the Output
    • 3.2 Key Generation Examples (Different Platforms)
      • 3.2.1 Generating an Ed25519 Key on Linux/macOS
      • 3.2.2 Generating an RSA Key on Windows (Git Bash)
      • 3.2.3 Using PuTTYgen on Windows
  4. Adding Your SSH Public Key to GitLab

    • 4.1 Locating and Copying Your Public Key
      • 4.1.1 Showing your public key (cat)
      • 4.1.2 Copying the Key to Your Clipboard (Various Methods)
    • 4.2 Navigating to Your GitLab SSH Key Settings
    • 4.3 Pasting and Adding the Key
    • 4.4 Setting an Optional Title and Expiration Date
    • 4.5 Verifying the Key Fingerprint
  5. Testing Your SSH Connection

    • 5.1 Using the ssh Command to Test the Connection
    • 5.2 Understanding the Welcome Message
    • 5.3 Troubleshooting Connection Issues
      • 5.3.1 Permission denied (publickey)
      • 5.3.2 Connection refused
      • 5.3.3 Agent forwarding issues
      • 5.3.4 Incorrect key
      • 5.3.5 Firewall problems
  6. Cloning Repositories Using SSH

    • 6.1 Finding the SSH Clone URL
    • 6.2 Using git clone with the SSH URL
    • 6.3 First-Time Clone: Accepting the Host Key
    • 6.4 Pushing and Pulling with SSH
  7. Using an SSH Agent (Optional but Recommended)

    • 7.1 What is an SSH Agent?
    • 7.2 Starting the SSH Agent
      • 7.2.1 On Linux and macOS
      • 7.2.2 On Windows (Git Bash, Pageant)
    • 7.3 Adding Your Private Key to the Agent (ssh-add)
    • 7.4 Verifying Keys Loaded in the Agent (ssh-add -l)
    • 7.5 Automating Agent Startup
    • 7.5.1 Linux and macOS (.bashrc, .zshrc, config)
    • 7.5.2 Windows (Startup folder, registry)
  8. Managing Multiple SSH Keys (for Different Projects or Servers)

    • 8.1 Creating Separate Key Pairs
    • 8.2 Configuring SSH Config File (~/.ssh/config)
      • 8.2.1 Defining Host Aliases
      • 8.2.2 Specifying Identity Files
      • 8.2.3 Setting Usernames
      • 8.2.4 Example Configuration
    • 8.3 Using Different Keys with GitLab
  9. SSH Key Security Best Practices

    • 9.1 Always Use a Strong Passphrase
    • 9.2 Protect Your Private Key File
    • 9.3 Regularly Rotate Your Keys
    • 9.4 Use an SSH Agent for Convenience and Security
    • 9.5 Limit Key Usage (Specific Projects/Servers)
    • 9.6 Monitor Your SSH Key Activity in GitLab
    • 9.7 Revoke Keys When No Longer Needed
    • 9.8 Use hardware security keys (like YubiKey)
  10. Troubleshooting and Advanced Topics

    • 10.1 Dealing with “Permission denied (publickey,keyboard-interactive)”
    • 10.2 Fixing “Connection refused” Errors
    • 10.3 Working with SSH Keys in Docker Containers
    • 10.4 Using SSH Keys with CI/CD Pipelines
    • 10.5 Understanding SSH Key Fingerprints
    • 10.6 Debugging SSH with Verbose Output (ssh -v)
    • 10.7 Configuring GitLab Server-Side SSH Settings (For Administrators)
    • 10.8 Dealing with passphrase prompts when they shouldn’t appear.
  11. Conclusion


1. Introduction: Why Use SSH Keys with GitLab?

SSH keys provide a secure and efficient way to authenticate with GitLab, eliminating the need to repeatedly enter your username and password. This section explains the benefits of SSH keys and the fundamental concepts behind them.

1.1 The Problems with Password Authentication

Traditional password-based authentication for Git operations (cloning, pushing, pulling) has several drawbacks:

  • Inconvenience: Typing your password for every interaction with GitLab is tedious and time-consuming.
  • Security Risks:
    • Weak Passwords: Users often choose weak or easily guessable passwords.
    • Password Reuse: Reusing the same password across multiple services is a major security vulnerability.
    • Phishing Attacks: You might be tricked into entering your password on a fake GitLab login page.
    • Keyloggers: Malware can record your keystrokes, capturing your password.
    • Plaintext Transmission (Without HTTPS): If you’re not using HTTPS (which you should be), your password could be intercepted in transit.

1.2 The Advantages of SSH Key Authentication

SSH key authentication offers significant improvements over password-based authentication:

  • Enhanced Security: SSH keys use public-key cryptography, making them far more secure than passwords. The private key is never transmitted over the network.
  • Convenience: Once set up, you can interact with GitLab without entering your password for each operation (especially when using an SSH agent).
  • Automation: SSH keys are essential for automated processes, such as CI/CD pipelines, where manual password entry is not feasible.
  • Access Control: You can manage multiple SSH keys, granting different levels of access to different projects or servers.
  • Two-Factor Authentication (2FA) Compatibility: SSH keys can work seamlessly with 2FA, providing an additional layer of security.

1.3 Understanding the Concept of Public-Key Cryptography

SSH keys rely on public-key cryptography (also known as asymmetric cryptography). This involves a pair of mathematically related keys:

  • Private Key: This key is kept secret on your local machine. It’s like your digital signature. You should never share it with anyone. It’s usually protected by a passphrase.
  • Public Key: This key can be shared publicly. It’s like your digital ID card. You add this key to services like GitLab.

The magic of public-key cryptography is that data encrypted with the public key can only be decrypted with the corresponding private key, and vice-versa. This ensures that only the holder of the private key can prove their identity.

1.4 SSH and GitLab: How They Work Together

Here’s a simplified explanation of how SSH authentication works with GitLab:

  1. Key Generation: You generate an SSH key pair (private and public) on your local machine.
  2. Public Key Upload: You upload the public key to your GitLab account.
  3. Connection Request: When you try to connect to GitLab (e.g., to clone a repository), your SSH client uses your private key to initiate the connection.
  4. Challenge-Response: GitLab sends a challenge (a random piece of data encrypted with your public key).
  5. Decryption and Proof: Your SSH client uses your private key to decrypt the challenge and sends the decrypted result back to GitLab.
  6. Authentication: GitLab verifies that the decrypted response is correct. If it is, you are authenticated, and access is granted.

This process happens behind the scenes, providing a secure and seamless authentication experience.

2. Prerequisites

Before you begin, ensure you have the following:

2.1 A GitLab Account

You need a GitLab account (either on GitLab.com or a self-hosted GitLab instance) to add your SSH key.

2.2 Git Installed on Your Local Machine

Git is the version control system that GitLab uses. You’ll need Git installed on your local computer to interact with GitLab repositories. You can download Git from https://git-scm.com/downloads.

2.3 An SSH Client (Usually Included with Git)

An SSH client is a program that allows you to connect to remote servers using the SSH protocol. Most Git installations include an SSH client (like OpenSSH).

  • Linux/macOS: OpenSSH is typically pre-installed.
  • Windows: Git Bash (included with Git for Windows) provides OpenSSH. You can also use PuTTY.

2.4 Operating System Considerations (Windows, macOS, Linux)

While the core concepts are the same, there are minor differences in how you interact with the command line and manage SSH keys on different operating systems:

  • Linux: Uses a terminal (e.g., Bash, Zsh). SSH keys are typically stored in ~/.ssh/.
  • macOS: Uses a terminal (e.g., Terminal.app, iTerm2). SSH keys are typically stored in ~/.ssh/.
  • Windows:
    • Git Bash: Provides a Unix-like environment with OpenSSH. Recommended for consistency with Linux/macOS. SSH keys are typically stored in ~/.ssh/ (which translates to C:\Users\<your_username>\.ssh\).
    • PuTTY: A popular alternative SSH client for Windows. Uses a different key format (.ppk) and requires PuTTYgen for key generation and Pageant for agent functionality. This guide primarily focuses on Git Bash for Windows.
    • Windows Subsystem for Linux (WSL): If you are using WSL, then follow the Linux instructions.

3. Generating Your SSH Key Pair

This section provides detailed instructions on generating your SSH key pair.

3.1 Step-by-Step Key Generation (All Platforms)

3.1.1 Opening Your Terminal or Command Prompt

  • Linux/macOS: Open your terminal application (e.g., Terminal, iTerm2, Konsole, GNOME Terminal).
  • Windows (Git Bash): Right-click in any folder and select “Git Bash Here,” or search for “Git Bash” in the Start menu.

3.1.2 Using the ssh-keygen Command

The ssh-keygen command is used to generate SSH key pairs. Here’s the basic command:

bash
ssh-keygen -t <key_type> -b <key_size> -C "[email protected]"

  • -t <key_type>: Specifies the type of key to generate. Common options are:
    • rsa: A widely used algorithm. A key size of at least 2048 bits is recommended (4096 is better).
    • ed25519: A more modern and generally preferred algorithm. It offers better security and performance than RSA with smaller key sizes. This is the recommended option.
    • ecdsa: Another algorithm, but Ed25519 is generally favored.
  • -b <key_size>: Specifies the key size (in bits) for RSA keys. Not needed for Ed25519.
  • -C "[email protected]": Adds a comment to the key. This is often your email address and helps identify the key. The comment is not used for authentication; it’s purely informational.

3.1.3 Choosing a Key Type (RSA, Ed25519)

Recommendation: Use Ed25519. It’s more secure and efficient than RSA. If you must use RSA (e.g., for compatibility with older systems), use a key size of at least 4096 bits.

3.1.4 Specifying a File Location

By default, ssh-keygen will save the keys in the ~/.ssh/ directory:

  • Private Key: ~/.ssh/id_ed25519 (or ~/.ssh/id_rsa)
  • Public Key: ~/.ssh/id_ed25519.pub (or ~/.ssh/id_rsa.pub)

You can specify a different file location using the -f option:

bash
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/my_gitlab_key

This will create ~/.ssh/my_gitlab_key (private) and ~/.ssh/my_gitlab_key.pub (public).

3.1.5 Setting a Passphrase (Recommended)

ssh-keygen will prompt you to enter a passphrase. A passphrase is highly recommended. It adds an extra layer of security to your private key. If your private key file is ever compromised, the attacker will also need the passphrase to use it.

  • Strong Passphrase: Use a long, complex passphrase that is not easily guessable. Consider using a password manager to generate and store a strong passphrase.
  • Empty Passphrase: You can create a key without a passphrase (by pressing Enter twice), but this is strongly discouraged for security reasons.

3.1.6 Understanding the Output

ssh-keygen will display output similar to this:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/user/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user/.ssh/id_ed25519.
Your public key has been saved in /home/user/.ssh/id_ed25519.pub.
The key fingerprint is:
SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX [email protected]
The key's randomart image is:
+--[ED25519 256]--+
| . |
| + . |
| . o . |
| . . o . |
| o . S . |
| . o + . |
| E . o = |
| . o = + |
| . + o. |
+----[SHA256]-----+

  • File Paths: The output shows where the private and public keys were saved.
  • Key Fingerprint: A unique identifier for your public key. You can use this to verify that you’ve added the correct key to GitLab.
  • Randomart Image: A visual representation of the key fingerprint. It’s less precise than the fingerprint but can be helpful for quick visual comparisons.

3.2 Key Generation Examples (Different Platforms)

3.2.1 Generating an Ed25519 Key on Linux/macOS

bash
ssh-keygen -t ed25519 -C "[email protected]"

Follow the prompts to enter a passphrase (recommended) and confirm the file location (default is fine).

3.2.2 Generating an RSA Key on Windows (Git Bash)

bash
ssh-keygen -t rsa -b 4096 -C "[email protected]"

Follow the prompts to enter a passphrase (recommended) and confirm the file location (default is fine).

3.2.3 Using PuTTYgen on Windows
PuTTYgen provides a graphical interface for generating keys. If you are not using Git Bash, this is how you’d generate keys. This is not the recommended approach, as Git Bash offers a more consistent experience.

  1. Download and Install PuTTY: Download PuTTY from https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html. You’ll need putty.exe and puttygen.exe.
  2. Run PuTTYgen: Open puttygen.exe.
  3. Select Key Type:
    • RSA: Select “RSA” and set “Number of bits in a generated key” to 4096.
    • Ed25519: Select “Ed25519”.
  4. Generate Key: Click the “Generate” button and move your mouse around randomly to generate entropy.
  5. Enter Key Comment: In the “Key comment” field, enter your email address (e.g., [email protected]).
  6. Enter Key Passphrase: Enter a strong passphrase in the “Key passphrase” and “Confirm passphrase” fields.
  7. Save Private Key: Click “Save private key” and choose a secure location to save the .ppk file (e.g., C:\Users\<your_username>\.ssh\my_gitlab_key.ppk).
  8. Copy Public Key: The public key is displayed in the “Public key for pasting into OpenSSH authorized_keys file” box. Copy this entire text. This is what you’ll add to GitLab.
  9. Save Public key (Optional): You can optionally click “Save public key” to save the public key, but you’ll be copying the key directly from the text box anyway.

4. Adding Your SSH Public Key to GitLab

Now that you have generated your SSH key pair, you need to add the public key to your GitLab account.

4.1 Locating and Copying Your Public Key

4.1.1 Showing your public key (cat)
You can view the contents of your public key file using the cat command in your terminal:

bash
cat ~/.ssh/id_ed25519.pub # For Ed25519
cat ~/.ssh/id_rsa.pub # For RSA

This will display the public key, which starts with ssh-ed25519 or ssh-rsa and ends with your comment (usually your email address).

4.1.2 Copying the Key to Your Clipboard (Various Methods)

You need to copy the entire public key to your clipboard so you can paste it into GitLab. Here are some ways to do this:

  • Linux:
    bash
    cat ~/.ssh/id_ed25519.pub | xclip -selection clipboard # Using xclip
    cat ~/.ssh/id_ed25519.pub | xsel -ib # Using xsel
  • macOS:
    bash
    pbcopy < ~/.ssh/id_ed25519.pub
  • Windows (Git Bash):
    bash
    cat ~/.ssh/id_ed25519.pub | clip
  • Manual Copy: You can also manually select the entire public key text in the terminal and copy it using Ctrl+C (or Cmd+C on macOS) or right-click and select “Copy.” Make sure you copy the entire key, including the ssh-ed25519 or ssh-rsa prefix and your email address at the end.

4.2 Navigating to Your GitLab SSH Key Settings

  1. Log in to GitLab: Go to https://gitlab.com (or your self-hosted GitLab instance) and log in to your account.
  2. Go to User Settings: Click on your profile picture in the top-right corner and select “Preferences”.
  3. Go to SSH Keys: In the left sidebar, click on “SSH Keys”.

4.3 Pasting and Adding the Key

  1. Paste the Key: In the “Key” text box, paste the entire public key that you copied to your clipboard.
  2. Click “Add key”: Click the “Add key” button.

4.4 Setting an Optional Title and Expiration Date

  • Title: You can give your key a descriptive title (e.g., “My Laptop,” “Work Computer”). This helps you identify the key later. This field is optional but recommended.
  • Expiration Date: You can set an optional expiration date for your key. This is a good security practice, as it forces you to rotate your keys periodically. If you set an expiration date, GitLab will notify you before the key expires.

4.5 Verifying the Key Fingerprint

After adding the key, GitLab will display the key fingerprint. Verify that this fingerprint matches the fingerprint displayed by ssh-keygen when you generated the key. This ensures that you added the correct key. If the fingerprints don’t match, remove the key from GitLab and double-check that you copied the correct public key.

5. Testing Your SSH Connection

After adding your public key to GitLab, it’s crucial to test the connection to ensure everything is working correctly.

5.1 Using the ssh Command to Test the Connection

Open your terminal (or Git Bash on Windows) and run the following command:

bash
ssh -T [email protected]

  • -T: Disables pseudo-terminal allocation, which is not needed for this test.
  • [email protected]: This is the SSH host for GitLab.com. If you’re using a self-hosted GitLab instance, replace gitlab.com with your instance’s domain name.

5.2 Understanding the Welcome Message

If the connection is successful, you should see a welcome message similar to this:

Welcome to GitLab, @your_username!

This confirms that your SSH key is correctly configured and that you can authenticate with GitLab.

5.3 Troubleshooting Connection Issues

If the connection fails, you’ll likely see an error message. Here are some common issues and how to resolve them:

5.3.1 Permission denied (publickey)

This is the most common error. It means that GitLab could not authenticate you using your SSH key. Here are the most likely causes and solutions:

  • Incorrect Public Key: Make sure you copied the entire public key to GitLab, including the ssh-ed25519 or ssh-rsa prefix and your email address. Double-check the key fingerprint.
  • Private Key Permissions: Your private key file (~/.ssh/id_ed25519 or ~/.ssh/id_rsa) should have restricted permissions. Only you should be able to read and write it. Use the following command to set the correct permissions:
    bash
    chmod 600 ~/.ssh/id_ed25519 # Or ~/.ssh/id_rsa
    chmod 700 ~/.ssh
  • Incorrect Private Key Location: Make sure your SSH client is looking for the private key in the correct location. By default, it looks in ~/.ssh/. If you used a different location with ssh-keygen -f, you might need to specify the key file using the -i option:
    bash
    ssh -T -i ~/.ssh/my_gitlab_key [email protected]
  • SSH Agent Not Running or Key Not Added: If you’re using an SSH agent (recommended), make sure it’s running and that your private key is added to it. See Section 7 for details on using an SSH agent.
  • Wrong username: Make sure you are using the correct username, git. The username is not your GitLab username.

5.3.2 Connection refused

This error indicates that the SSH server (GitLab.com or your self-hosted instance) is not accepting connections on the SSH port (usually port 22).

  • Firewall Issues: A firewall on your local machine, your network, or the GitLab server might be blocking connections on port 22. Check your firewall settings.
  • GitLab Server Down: GitLab.com might be experiencing downtime, or your self-hosted GitLab instance might be offline.
  • Incorrect Hostname: Double-check that you’re using the correct hostname (gitlab.com or your self-hosted instance’s domain name).
  • SSH Not Enabled on Server: If you are using a self-hosted instance, ensure that SSH is enabled and running on the server.

5.3.3 Agent forwarding issues

Agent forwarding allows you to use your local SSH keys on a remote server without copying your private key to the remote server. This is generally not needed for basic GitLab access and can be a security risk if not used carefully. If you see errors related to agent forwarding, and you are not intending to use this feature, try disabling it:

bash
ssh -T -o ForwardAgent=no [email protected]

5.3.4 Incorrect key

This error means your private key is not the corresponding key for the public key registered on GitLab. You are trying to use the wrong key. Check your ~/.ssh/config if you have one and ensure you are using the correct private key file.

5.3.5 Firewall problems

This is similar to “Connection refused” but might manifest differently depending on your firewall configuration. Make sure that outgoing connections on port 22 are allowed.

6. Cloning Repositories Using SSH

Once your SSH connection is working, you can clone repositories using the SSH URL.

6.1 Finding the SSH Clone URL

  1. Go to the Repository: In GitLab, navigate to the repository you want to clone.
  2. Click the “Clone” Button: Click the blue “Clone” button.
  3. Select “Clone with SSH”: Make sure the “Clone with SSH” option is selected. The URL will look like this:
    [email protected]:your_username/your_repository.git

6.2 Using git clone with the SSH URL

In your terminal, use the git clone command with the SSH URL:

bash
git clone [email protected]:your_username/your_repository.git

Replace your_username/your_repository.git with the actual SSH URL from GitLab.

6.3 First-Time Clone: Accepting the Host Key

The first time you connect to a new SSH host (like gitlab.com), you’ll be asked to verify the host key fingerprint:

The authenticity of host 'gitlab.com (172.65.251.78)' can't be established.
ED25519 key fingerprint is SHA256:eUXGGm1YGsMAS7vkcx6JOJdOGHPem5gQp4taiCfCLB8.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

  • Verify the Fingerprint: Compare the fingerprint displayed in the terminal with the fingerprint listed on GitLab’s documentation or your self-hosted instance’s documentation. This is a crucial security step. If the fingerprints match, type yes and press Enter. This adds gitlab.com to your ~/.ssh/known_hosts file, so you won’t be prompted again for this host.
  • If the Fingerprints Don’t Match: Do not type yes. This could indicate a man-in-the-middle attack. Contact your GitLab administrator or investigate the issue further.

6.4 Pushing and Pulling with SSH

After cloning a repository using SSH, subsequent git push and git pull operations will also use SSH authentication. You won’t need to enter your password if you have an SSH agent configured or if you entered the passphrase for your private key during the initial connection.

7. Using an SSH Agent (Optional but Recommended)

An SSH agent is a program that runs in the background and holds your decrypted private keys in memory. This eliminates the need to enter your passphrase every time you interact with GitLab.

7.1 What is an SSH Agent?

The SSH agent:

  • Improves Convenience: You only need to enter your passphrase once when you add the key to the agent.
  • Enhances Security: The decrypted private key is stored in memory, not on disk, making it less vulnerable to theft.
  • Facilitates Automation: Essential for scripts and automated processes that require SSH access.

7.2 Starting the SSH Agent

7.2.1 On Linux and macOS

The SSH agent is usually started automatically by your desktop environment or login shell. You can check if it’s running using:

bash
echo $SSH_AUTH_SOCK

If this command returns a path, the agent is running. If it’s empty, you can start the agent manually:

bash
eval "$(ssh-agent -s)"

7.2.2 On Windows (Git Bash, Pageant)

  • Git Bash: You can start the agent manually using the same command as Linux/macOS:
    bash
    eval "$(ssh-agent -s)"
  • Pageant (PuTTY): Pageant is the SSH agent that comes with PuTTY.
    1. Start Pageant: Find pageant.exe in your PuTTY installation directory and run it. It will appear as an icon in your system tray.
    2. Add Key: Right-click the Pageant icon in the system tray and select “Add Key”. Browse to your .ppk private key file and enter your passphrase.

7.3 Adding Your Private Key to the Agent (ssh-add)

Once the agent is running, you need to add your private key to it:

bash
ssh-add ~/.ssh/id_ed25519 # Or ~/.ssh/id_rsa, or your custom key path

You’ll be prompted for your passphrase. After entering the passphrase, the key is loaded into the agent.

If you are using Pageant on Windows, the key is added when you load the key file as described above.

7.4 Verifying Keys Loaded in the Agent (ssh-add -l)

You can check which keys are currently loaded in the agent using:

bash
ssh-add -l

This will list the fingerprints of the loaded keys.

7.5 Automating Agent Startup

To avoid manually starting the agent and adding your key every time you log in, you can automate the process.

7.5.1 Linux and macOS (.bashrc, .zshrc, config)

Add the following lines to your shell’s configuration file (e.g., ~/.bashrc, ~/.zshrc, ~/.config/fish/config.fish):

“`bash

Start SSH agent if not already running

if [ -z “$SSH_AUTH_SOCK” ]; then
eval “$(ssh-agent -s)”
fi

Add key to agent (replace with your key path)

ssh-add ~/.ssh/id_ed25519 &> /dev/null
“`

This script checks if the agent is running, starts it if necessary, and then adds your key. The &> /dev/null part suppresses output from ssh-add. You may need to enter your passphrase once after logging in, but subsequent SSH connections will use the agent without prompting.

7.5.2 Windows (Startup folder, registry)

  • Git Bash: Add the same lines as for Linux/macOS to your ~/.bashrc file (which is C:\Users\<your_username>\.bashrc in Git Bash).

  • Pageant (PuTTY – Autostart):

    1. Create a Shortcut: Create a shortcut to pageant.exe.
    2. Add Key to Shortcut: Right-click the shortcut, select “Properties,” and in the “Target” field, add the path to your .ppk file after pageant.exe, like this:
      "C:\Program Files\PuTTY\pageant.exe" "C:\Users\<your_username>\.ssh\my_gitlab_key.ppk"
    3. Place Shortcut in Startup Folder:
      • Press Win+R, type shell:startup, and press Enter. This opens your Startup folder.
      • Copy the Pageant shortcut into the Startup folder.

    Now, Pageant will start automatically when you log in and load your key. You’ll be prompted for your passphrase once.

8. Managing Multiple SSH Keys (for Different Projects or Servers)

It’s common to have multiple SSH keys for different purposes (e.g., personal projects, work projects, different servers). Here’s how to manage them effectively:

8.1 Creating Separate Key Pairs

Generate separate key pairs for each project or server, using the -f option with ssh-keygen to specify unique file names:

bash
ssh-keygen -t ed25519 -C "[email protected] (Project A)" -f ~/.ssh/project_a_key
ssh-keygen -t ed25519 -C "[email protected] (Server B)" -f ~/.ssh/server_b_key

8.2 Configuring SSH Config File (~/.ssh/config)

The SSH config file (~/.ssh/config) allows you to define settings for different SSH hosts, including which key to use. This is the best way to manage multiple keys.

8.2.1 Defining Host Aliases

You can create aliases for your hosts, making it easier to connect:

“`
Host gitlab-project-a
HostName gitlab.com
User git
IdentityFile ~/.ssh/project_a_key

Host

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top