Showing posts with label git. Show all posts
Showing posts with label git. Show all posts

March 23, 2025

Managing Multiple SSH Git Accounts on One Machine (For Nerds)

If you work with multiple Git accounts (e.g., personal, work, open-source contributions), managing SSH keys efficiently is crucial. This guide provides an in-depth look into setting up multiple SSH keys for different Git accounts, debugging common issues, and understanding SSH authentication at a deeper level.


1. Why You Need Multiple SSH Keys for Git

GitHub, GitLab, and Bitbucket allow SSH authentication, eliminating the need to enter credentials repeatedly. However, when you have multiple accounts, using the same SSH key across them may lead to conflicts.

For instance:

  • You might need different keys for personal and work repositories.
  • Some organizations enforce separate SSH keys for security.
  • You contribute to multiple projects and want isolated access.

Is This the Best Way? Are There Alternatives?

Using SSH keys is one of the most secure and convenient methods for authentication. However, there are other ways to manage multiple Git accounts:

  1. Using HTTPS & Git Credential Helper: Instead of SSH, you can authenticate using HTTPS and a credential helper to store your passwords securely.

    • Pros: No need to configure SSH.
    • Cons: Requires entering credentials periodically or using a credential manager.
  2. Using Different User Profiles: You can create separate user profiles on your machine and configure different Git settings for each.

    • Pros: Full isolation between accounts.
    • Cons: More cumbersome, requires switching users frequently.
  3. Using SSH Key Switching Manually: Instead of configuring ~/.ssh/config, you can manually specify the SSH key during each Git operation.

    • Example:
      GIT_SSH_COMMAND="ssh -i ~/.ssh/id_ed25519_work" git clone git@github.com:workuser/repo.git
      
    • Pros: No persistent configuration needed.
    • Cons: Requires specifying the key for every command.

Using ~/.ssh/config remains the most automated and hassle-free solution, making SSH authentication seamless across multiple accounts.


2. Generating Multiple SSH Keys

Each SSH key is a cryptographic pair consisting of a private and public key. To create separate keys for different accounts:

ssh-keygen -t ed25519 -C "your-email@example.com"

When prompted:

  • File to save the key: Choose a unique filename, e.g., ~/.ssh/id_ed25519_work for a work account and ~/.ssh/id_ed25519_personal for a personal account.
  • Passphrase: You can add one for extra security.

Example:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/yourname/.ssh/id_ed25519): ~/.ssh/id_ed25519_work
Enter passphrase (empty for no passphrase):

3. Adding SSH Keys to SSH Agent

Ensure the SSH agent is running:

eval "$(ssh-agent -s)"

Then, add your newly generated SSH keys:

ssh-add ~/.ssh/id_ed25519_work
ssh-add ~/.ssh/id_ed25519_personal

To list currently added SSH keys:

ssh-add -l

If you see The agent has no identities, restart the SSH agent and re-add the keys.


4. Configuring SSH for Multiple Git Accounts

Modify or create the SSH configuration file:

nano ~/.ssh/config

Add the following entries:

# Personal GitHub Account
Host github-personal
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_personal

# Work GitHub Account
Host github-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_work
  • Host github-personal: This is a custom alias for GitHub personal use.
  • IdentityFile ~/.ssh/id_ed25519_personal: Specifies the SSH key to use.
  • HostName github.com: The real hostname of GitHub.

Now, Git will use the correct key automatically.


5. Adding SSH Keys to GitHub / GitLab

Each Git service requires adding your public key for authentication.

Get the Public Key

To display the public key:

cat ~/.ssh/id_ed25519_work.pub

Copy the key and add it to GitHub / GitLab / Bitbucket under:

  • GitHub → Settings → SSH and GPG keys
  • GitLab → Profile → SSH Keys
  • Bitbucket → Personal Settings → SSH Keys

6. Cloning Repositories Using Multiple Accounts

When cloning a repository, use the custom alias instead of github.com:

# For personal account:
git clone git@github-personal:yourusername/personal-repo.git

# For work account:
git clone git@github-work:yourworkuser/work-repo.git

7. Testing SSH Connections

Verify that SSH authentication is working:

ssh -T git@github-personal
ssh -T git@github-work

Expected output:

Hi yourusername! You've successfully authenticated...

If you see a permission error, ensure the correct key is added to the SSH agent (ssh-add -l).


8. Fixing Common Issues

1. SSH Key Not Used Correctly

Run:

ssh -vT git@github-personal

If you see Permission denied (publickey), make sure:

  • The correct SSH key is added to the SSH agent.
  • The key is correctly configured in ~/.ssh/config.

2. Wrong Host in Git Remote URL

Check the remote URL:

git remote -v

If it shows github.com, update it:

git remote set-url origin git@github-work:yourworkuser/work-repo.git

3. Too Many Authentication Failures

If you have multiple SSH keys and face authentication failures, specify the identity explicitly:

ssh -i ~/.ssh/id_ed25519_work -T git@github.com

9. Advanced: Using Different Git Configurations Per Account

If you want different Git usernames and emails for each account:

git config --global user.name "Personal Name"
git config --global user.email "personal@example.com"

For work repos:

git config --local user.name "Work Name"
git config --local user.email "work@example.com"

This ensures commits from work and personal accounts are correctly attributed.


Final Thoughts

By configuring multiple SSH keys, you can seamlessly work with different Git accounts without switching credentials manually. Understanding SSH authentication helps prevent conflicts and ensures a smooth development workflow.

Happy coding! 🚀

March 4, 2025

Git: One-Stop Solution for Amending Commits, Rebasing, and Best Practices

Git is an essential tool for developers, but it can sometimes be confusing, especially for beginners or those new to advanced workflows like amending commits, rebasing, and handling SSH authentication. This guide will help you understand Git in a way that even a 10-year-old or a seasoned developer can follow. By the end, you'll have a future-ready workflow for handling Git like a pro.


1️⃣ Understanding Git Simply

Think of Git like a time machine for your code. Every time you save changes (commit), you're creating a snapshot of your project. If something goes wrong, you can travel back in time and restore your project. Cool, right? 🚀


2️⃣ Amending a Commit (Fixing a Mistake 🛠️)

Sometimes, you commit a change and realize, "Oops! I forgot to add a file" or "I need to tweak my message." Instead of creating a new commit, you can amend the last one:

git commit --amend

If you just want to add new changes without modifying the commit message:

git commit --amend --no-edit

🔴 Warning: If you've already pushed the commit, you need to force push:

git push --force

Use this only when working alone or after notifying your team. Otherwise, it can rewrite history and mess up others’ work.


3️⃣ Rebasing (Keeping History Clean 📜)

Rebasing is like cleaning up your code's history before sharing it with others. Instead of showing every small step, it makes your changes look like they were made in an organized way.

✨ How to Rebase Interactively:

git rebase -i HEAD~N

🔹 Replace N with the number of commits you want to modify. 🔹 Options you’ll see:

  • pick → Keep commit as it is.
  • reword → Change commit message.
  • edit → Modify the commit’s content.
  • squash → Merge commits into the previous one.
  • drop → Remove commit.

🤔 When to Use Rebase vs Merge?

  • Rebase (Good for personal branches, keeps history clean)
  • Merge (Good for shared branches, keeps commit history intact)

To rebase onto main:

git checkout feature-branch
git rebase main

If there are conflicts:

git rebase --continue

4️⃣ Setting Up SSH for Secure Git Access 🔐

Using SSH lets you push and pull code securely without typing passwords every time.

✅ Steps to Set Up SSH:

  1. Check if SSH keys already exist:
    ls -al ~/.ssh
    
  2. Generate a new SSH key (if needed):
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    
  3. Add SSH key to agent:
    eval "$(ssh-agent -s)"
    ssh-add ~/.ssh/id_rsa
    
  4. Copy the SSH key and add it to GitHub/GitLab:
    cat ~/.ssh/id_rsa.pub
    
  5. Test the SSH connection:
    ssh -T git@github.com
    
    If successful, you should see:
    Hi <username>! You've successfully authenticated.
    

5️⃣ Must-Know Git Cheat Sheet 📜

📌 Essential Git Commands

git clone <repo_url>   # Copy a repository to your machine
git status             # Check status of files
git add .              # Add all files to staging
git commit -m "Message" # Commit changes
git push origin <branch> # Push changes

⏪ Undo Mistakes

git reset --soft HEAD~1  # Undo last commit, keep changes
git reset --hard HEAD~1  # Undo last commit, discard changes
git checkout -- .        # Discard uncommitted changes

🔀 Branch Management

git branch <new-branch>  # Create new branch
git checkout <branch>    # Switch branch
git merge <branch>       # Merge branches

💾 Stashing (Temporary Save)

git stash                # Save changes temporarily
git stash pop            # Restore saved changes

📜 View Logs

git log --oneline --graph --decorate --all

6️⃣ Best Practices for a Future-Ready Git Workflow 🏆

Write Meaningful Commit Messages

  • BAD: fixed bug
  • GOOD: Fixed login issue causing incorrect redirection

Commit Only What’s Necessary

  • Avoid committing .env, node_modules/, or .DS_Store

Use Branches for Features and Fixes

  • Keep main stable, work on feature-xyz branches

Rebase Before Merging to Keep History Clean

git rebase main

Use git pull --rebase Instead of git pull

  • Avoids unnecessary merge commits

Use git push --force-with-lease Instead of git push --force

  • Prevents accidental overwrites by checking if someone else pushed first

Tag Releases for Easier Debugging

git tag -a v1.0 -m "Release version 1.0"
git push origin v1.0

Set Up .gitignore to Avoid Unwanted Files

echo "node_modules/" >> .gitignore
git rm -r --cached node_modules/

Regularly Prune Old Branches

git branch -d old-branch

Automate Git Hooks for Code Formatting & Security Checks

cp pre-commit .git/hooks/
chmod +x .git/hooks/pre-commit

🎯 Conclusion

Git doesn’t have to be intimidating! With these best practices, cheats, and SSH setup, you now have a future-ready workflow that will make your life easier as a developer. 🚀

🔹 Keep your commits clean. 🔹 Use branches wisely. 🔹 Secure your repo with SSH. 🔹 Automate where possible.

Happy coding! 🎉

February 12, 2025

The Best Strategy for Branch Deployment in QA, Pre-Prod, and Prod

In modern software development, efficient branch deployment is crucial for maintaining a smooth development cycle while ensuring quality and stability. A well-defined branching strategy helps teams manage deployments effectively, reduce conflicts, and improve collaboration between developers, testers, and operations teams. This blog will outline the best and easiest-to-handle strategy for branch deployment, focusing on fewer steps and a streamlined Dev-to-Prod pipeline.




Why a Simplified Deployment Strategy Matters?

  1. Reduces Complexity – Fewer branches mean less confusion.
  2. Faster Time to Production – Automates testing and approvals.
  3. Ensures Stability – Prevents unfinished code from reaching production.
  4. Supports Quick Fixes – Hotfixes are easy to apply.
  5. Improves Collaboration – Developers, testers, and DevOps work seamlessly.
  6. Enhances Code Quality – Ensures tested and stable features reach production.

Latest and Simplified Branching Strategy

1. Branch Structure

To optimize deployment speed, we follow a streamlined approach:

  • main (or master) – Always production-ready.
  • Feature branches (feature/XYZ) – Developers work on new features.
  • QA branch (qa) – All feature branches merge here for initial testing.
  • Pre-Prod branch (pre-prod) – Stable, tested code moves here before production release.
  • Hotfix branches (hotfix/XYZ) – Urgent fixes branched from main.

2. Workflow for Deployment

Dev to QA Deployment Process

  1. Developers create feature branches from main.
  2. After local testing, feature branches are merged into qa.
  3. QA testing is performed on qa, and fixes are pushed directly to qa.
  4. Once QA approves, qa is merged into pre-prod for staging validation.

Pre-Prod to Prod Deployment Process

  1. Once testing in pre-prod is complete, pre-prod is merged into main.
  2. Production deployment is triggered via CI/CD.
  3. If issues are found in Production, fixes are applied via hotfix/XYZ and merged into main, pre-prod, and qa.
  4. CI/CD ensures automated rollback in case of failures.

CI/CD Pipeline Integration

A robust CI/CD pipeline should automate deployments based on branch activities:

  • QA: Auto-deploy builds from qa for initial testing.
  • Pre-Prod: Auto-deploy from pre-prod for staging.
  • Production: Auto-deploy from main after approval.

Key Steps:

  • Automated Testing: Runs on every merge, including unit, integration, and regression tests.
  • Code Quality Checks: Ensures best practices using tools like SonarQube, ESLint, or Checkstyle.
  • Security Scanning: Identifies vulnerabilities before deployment.
  • Approval Gates: Manual approval before going live in production.
  • Blue-Green Deployment: Ensures zero downtime releases.
  • Canary Releases: Gradually roll out changes to a subset of users before full deployment.

Best Practices for Easy Handling

  1. Minimal Branches – Stick to main, qa, pre-prod, and feature/*.
  2. Use Trunk-Based Development – Avoid long-lived branches.
  3. Automate Everything – CI/CD handles deployments, testing, and security scanning.
  4. Quick Rollbacks – Use feature flags and automated rollbacks.
  5. Sync Environments – Ensure qa, pre-prod, and prod stay aligned.
  6. Monitor Performance – Use APM tools (New Relic, Datadog) to track issues.
  7. Infrastructure as Code (IaC) – Automate environment provisioning using Terraform or Ansible.
  8. Document Everything – Maintain clear deployment playbooks for the team.

Conclusion

A streamlined branch deployment strategy reduces complexity, improves efficiency, and ensures high-quality production releases. By minimizing the number of branches, integrating a robust CI/CD pipeline, and adopting best practices like automated testing, blue-green deployments, and canary releases, teams can achieve a seamless Dev-to-Prod workflow with minimal manual steps.

What branching strategy do you follow? Let us know in the comments!