Managing Multiple GitLab Identities for Home and Work

Managing Multiple GitLab Identities for Home and Work

Table of Contents

Many developers need to interact with GitLab using different identities – a personal account for passion projects and a work account for professional endeavors. Juggling these can be cumbersome, leading to accidental commits with the wrong email or access issues. This guide provides a step-by-step approach to configuring your system to seamlessly manage multiple GitLab profiles, automatically selecting the correct SSH keys and user configurations based on the repository’s location.

The Goal

Our aim is to achieve a setup where:

  1. Separate SSH keys are used for your personal and work GitLab accounts.
  2. Your system automatically selects the correct SSH key when interacting with GitLab.com, depending on which identity is appropriate.
  3. Git commits are authored with the correct email and name associated with the active identity for a given repository.

Prerequisites

  • You have two separate GitLab accounts (e.g., username_home and username_work).
  • git is installed on your system.
  • ssh client is installed on your system.
  • You are comfortable working in the terminal.

Step 1: Generate Separate SSH Keys

First, we’ll create distinct SSH keys for each GitLab identity. It’s good practice to use strong Ed25519 keys.

Open your terminal and execute the following commands. When prompted for a passphrase, it’s highly recommended to set one for better security.

# Create SSH key for your work GitLab account
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_gitlab_work -C "your_work_email@example.com"

# Create SSH key for your personal GitLab account
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_gitlab_home -C "your_personal_email@example.com"

# -t ed25519: Specifies the type of key to create, Ed25519 is a modern and secure choice.```
# -f ~/.ssh/id_ed25519_gitlab_work: Specifies the filename for the new key. Using a descriptive name helps in managing multiple keys.```
# -C "your_email@example.com": Adds a comment to the key, usually your email address, for easy identification.```

You will now have two new key pairs in your ~/.ssh directory:

id_ed25519_gitlab_work (private key) and id_ed25519_gitlab_work.pub (public key)

id_ed25519_gitlab_home (private key) and id_ed25519_gitlab_home.pub (public key)

Important: Never share your private keys!

Step 2: Add SSH Keys to Your GitLab Accounts

You need to add the respective public keys to your GitLab accounts.

For your work account:

Log in to GitLab.com with your work credentials. Navigate to your user settings: click your avatar > Edit profile > SSH Keys (or go directly to https://gitlab.com/-/profile/keys). Copy the content of your work public key:

cat ~/.ssh/id_ed25519_gitlab_work.pub

Paste the copied key into the “Key” field on GitLab, give it a descriptive title (e.g., “Work Laptop - Work Account”), and click “Add key”.

For your personal account:

Log out of your work GitLab account. Log in to GitLab.com with your personal credentials. Navigate to your user settings: click your avatar > Edit profile > SSH Keys (or go directly to https://gitlab.com/-/profile/keys). Copy the content of your personal public key:

cat ~/.ssh/id_ed25519_gitlab_home.pub

Paste the copied key into the “Key” field on GitLab, give it a descriptive title (e.g., “Work Laptop - Home Account”), and click “Add key”.

Step 3: Configure SSH to Use the Correct Keys

Now, we’ll tell SSH which key to use for which GitLab “host”. We achieve this by creating or editing your SSH configuration file (~/.ssh/config).

Open ~/.ssh/config in a text editor. If the file doesn’t exist, create it. Add the following configuration:

# Personal GitLab account
Host gitlab.com-home
  HostName gitlab.com
  User git
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/id_ed25519_gitlab_home
  IdentitiesOnly yes

# Work GitLab account
Host gitlab.com-work
  HostName gitlab.com
  User git
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/id_ed25519_gitlab_work
  IdentitiesOnly yes

# Optional: Default GitLab configuration (if you have a primary one or for other repos)
# Host gitlab.com
#   HostName gitlab.com
#   User git
#   PreferredAuthentications publickey
#   IdentityFile ~/.ssh/id_ed25519_gitlab_primary # Or one of the above if you prefer a default
#   IdentitiesOnly yes

Now you can test your connections:

ssh -T git@gitlab.com-home
# You should see a welcome message for your personal GitLab account.

ssh -T git@gitlab.com-work
# You should see a welcome message for your work GitLab account.

If you used passphrases for your keys, you’ll be prompted for them.

Entering your SSH key passphrase every time can be tedious. keychain is a utility that helps manage SSH agents, allowing you to enter your passphrases once per session.

Install keychain:

On Debian/Ubuntu: sudo apt-get install keychain

On macOS (using Homebrew): brew install keychain

For other systems, check your package manager. Configure keychain to load at shell startup: Add the following to your shell’s configuration file (e.g., ~/.bashrc, ~/.zshrc):

eval `keychain --eval --agents ssh id_ed25519_gitlab_home id_ed25519_gitlab_work`
# If you want keychain to manage all keys in ~/.ssh, you can use:
# eval `keychain --eval --agents ssh $(find ~/.ssh -type f -name "id_*" -not -name "*.pub" -exec basename {} \;)`

This line will:

Start ssh-agent if it’s not already running. Add your specified keys to the agent. If they are passphrase-protected, keychain will prompt you for the passphrases the first time they are loaded in a new session. Reload your shell configuration for the changes to take effect (e.g., source ~/.bashrc or open a new terminal).

Step 5: Configuring Git Repositories

Now we need to tell Git which remote URL (and thus which SSH alias) to use for your repositories.

For New Repositories: When cloning a new repository, use the appropriate SSH alias in the clone URL:

For a personal project:

git clone git@gitlab.com-home:your_personal_username/your_project.git
# Example: git clone git@gitlab.com-home:paulthomas/my-blog.git

For a work project:

git clone git@gitlab.com-work:your_work_group/your_project.git
# Example: git clone git@gitlab.com-work:acme-corp/internal-tool.git

For Existing Repositories:

If you have repositories that were cloned using the default gitlab.com URL, you’ll need to update their remote origin URL.

Navigate to your repository’s directory:

cd path/to/your/repository

Check the current remote URL:

git remote -v

You’ll likely see something like:

origin  git@gitlab.com:username/project.git (fetch)
origin  git@gitlab.com:username/project.git (push)

Update the remote URL to use your desired SSH alias:

If it’s a personal project:

git remote set-url origin git@gitlab.com-home:your_personal_username/your_project.git

If it’s a work project:

git remote set-url origin git@gitlab.com-work:your_work_group/your_project.git

Verify the change:

git remote -v

Step 6: Setting Per-Repository Git User Configuration (Name and Email)

Simply using the correct SSH key isn’t enough; you also want your commits to be attributed to the correct author (name and email). Git allows you to set this configuration per repository.

The most straightforward way is to configure it manually within each repository:

Inside your personal project repository:

cd path/to/your/personal_project
git config user.name "Your Personal Name"
git config user.email "your_personal_email@example.com"

Inside your work project repository:

cd path/to/your/work_project
git config user.name "Your Work Name"
git config user.email "your_work_email@example.com"

This ensures that any commits made in that specific repository will use these local settings, overriding any global Git configuration.

Advanced: Automatic Per-Repository Configuration with Conditional Includes (Git 2.13+)

For a more automated approach, if you organize your work and personal projects into distinct parent directories (e.g., ~/dev/personal/ and ~/dev/work/), you can use Git’s conditional includes feature.

Create separate Git configuration files for your identities:

~/.gitconfig-personal:

[user]
    name = Your Personal Name
    email = your_personal_email@example.com

~/.gitconfig-work:

[user]
    name = Your Work Name
    email = your_work_email@example.com
# You might also include other work-specific Git settings here
# For example, if your work uses a GPG key for signing commits:
# signingkey = YOUR_WORK_GPG_KEY_ID

Edit your global ~/.gitconfig file to include these conditionally:

[user]
    # Your global default name and email, if any (will be overridden by conditional includes)
    name = Your Default Name
    email = your_default_email@example.com

[includeIf "gitdir:~/dev/personal/"] # Note the trailing slash
    path = ~/.gitconfig-personal

[includeIf "gitdir:~/dev/work/"] # Note the trailing slash
    path = ~/.gitconfig-work

# Add other global configurations here
[core]
    editor = vim # or your preferred editor

How it works:

If your current Git repository is located anywhere under ~/dev/personal/, the settings from ~/.gitconfig-personal will be applied. If it’s under ~/dev/work/, settings from ~/.gitconfig-work will be applied. Otherwise, your global Git settings will be used. Adjust the paths (~/dev/personal/, ~/dev/work/) to match your directory structure.

Step 7: Handling Multiple Push Remotes

There is a more advanced Git feature that allows you to push to multiple remote locations simultaneously or have named push remotes.

# git remote set-url origin --push --add git@gitlab.com-home:mygroup/self-hosted/00-network.git
# git remote set-url origin --push --add git@gitlab.com-work:engineering/devops/gitlab/gitlab-self-hosted/00-network.git

Use Case:

This is useful if, for example, you want to push a repository to both your personal GitLab (using gitlab.com-home) and your work GitLab (using gitlab.com-work) with a single git push origin. Or, if a repository needs to mirror to different locations under different identities.

Explanation:

git remote set-url origin --push --add <url>: This command adds a new URL to the list of URLs that git push origin will push to. It doesn’t replace the existing fetch URL (used for git pull or git fetch). When you run git push origin, Git will attempt to push to all URLs configured for push under the remote named origin. Applying to our setup:

If you have a repository, let’s say my-project, and you want changes to be pushed to both your personal and work GitLab accounts (assuming the project exists in both places under potentially different paths):

Ensure your primary remote origin is set for fetching (usually your primary working location): Let’s assume origin primarily points to your personal account for fetching:

git remote set-url origin git@gitlab.com-home:your_personal_username/my-project.git

Add push URLs for both identities: First, re-add the push URL for the personal account explicitly (if set-url above only set the fetch URL, or if you want to be very clear):

git remote set-url --add --push origin git@gitlab.com-home:your_personal_username/my-project.git

Then, add the push URL for the work account:

git remote set-url --add --push origin git@gitlab.com-work:your_work_group/my-project.git

Now, git remote -v would show something like:

origin  git@gitlab.com-home:your_personal_username/my-project.git (fetch)
origin  git@gitlab.com-home:your_personal_username/my-project.git (push)
origin  git@gitlab.com-work:your_work_group/my-project.git (push)

When you run git push origin, Git will try to push to both gitlab.com-home and gitlab.com-work, using the correct SSH keys for each due to our ~/.ssh/config setup.

Caution with Multiple Push URLs

Ensure you have write access to all configured push URLs with the respective identities. This can make git push take longer if one of the remotes is slow or unavailable. It’s a powerful feature but can be confusing if not managed carefully. For most simple work/home separation, just ensuring the correct single remote for each repository (as in Step 5) is sufficient. Use multiple push URLs only when you explicitly need to mirror changes to multiple locations with different identities.

Conclusion

By following these steps, you’ve created a robust system for managing separate GitLab identities for your home and work projects. Your SSH connections will automatically use the correct keys based on custom host aliases, and your Git commits will be correctly attributed using per-repository or conditional configurations. This setup minimizes the risk of errors and streamlines your development workflow, allowing you to focus on your code.

Remember to adjust directory paths and email addresses to match your specific setup. Happy coding!

Related Posts

Building a Blog with Hugo and GitLab Pages

Building a Blog with Hugo and GitLab Pages

Setting up a personal blog doesn’t have to be expensive or complicated. In this guide, I’ll walk you through creating and hosting a blog using Hugo (a fast static site generator) and GitLab Pages (free hosting) - complete with a custom domain name and SSL certificate. The best part? Outside of the cost of a domain name it’s completely free!

Token-Zero: When you need a token to create a token

Token-Zero: When you need a token to create a token

When automating a GitLab installation, you’ll often need to create “token zero” - the first access token used to bootstrap your automation processes. Unlike the initial root password, this token is specifically scoped for API interactions during setup. This creates a chicken-and-egg situation: you need a token to make API calls, but you need to make an API call to create a token.

Navigating the GitLab repository

Navigating the GitLab repository

If you’ve ever needed to debug a GitLab issue or understand how a particular feature works, you’re in luck – GitLab’s open-source nature means all the answers are right there in the code. But with over 2 million lines of code spread across thousands of files, finding those answers can feel like searching for a needle in a particularly large and complex haystack.