Created
January 16, 2025 23:36
-
-
Save ei-grad/df732cc45684ecf8d081c360d94cfed6 to your computer and use it in GitHub Desktop.
Automate Deployment Key Setup for Multiple Git Repositories in GitHub Actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eo pipefail | |
if [[ $# -ne 1 ]]; then | |
echo "Usage: $0 <repo-name>" | |
exit 1 | |
fi | |
REPO_NAME="$1" | |
SSH_DIR="$HOME/.ssh" | |
GIT_CONFIG_FILE="$HOME/.gitconfig" | |
# Ensure .ssh directory exists | |
if [[ ! -d "$SSH_DIR" ]]; then | |
mkdir -p "$SSH_DIR" | |
chmod 700 "$SSH_DIR" | |
fi | |
# Read private key contents from stdin into a variable | |
SSH_PRIVATE_KEY_CONTENTS=$(cat) | |
REPO_NAME_HASHED=$(md5sum <<< $REPO_NAME | cut -d' ' -f1) | |
# Extract public key and save it to ~/.ssh/ | |
PUBLIC_KEY_FILE="$SSH_DIR/key-$REPO_NAME_HASHED.pub" | |
echo "$SSH_PRIVATE_KEY_CONTENTS" | ssh-keygen -y -f /dev/stdin > "$PUBLIC_KEY_FILE" | |
# Verify SSH_AUTH_SOCK is set and add the private key to ssh-agent | |
if [[ -z "$SSH_AUTH_SOCK" ]]; then | |
echo "Error: SSH_AUTH_SOCK is not set. Ensure ssh-agent is running and configured." | |
echo "You can start ssh-agent with: eval \$(ssh-agent -s)" | |
exit 1 | |
fi | |
echo "$SSH_PRIVATE_KEY_CONTENTS" | ssh-add - | |
REPO_GIT_CONFIG="$HOME/.gitconfig-$REPO_NAME_HASHED" | |
# Create a separate Git config for the repository | |
cat > "$REPO_GIT_CONFIG" <<EOF | |
[core] | |
sshCommand = ssh -i $PUBLIC_KEY_FILE -o IdentitiesOnly=yes | |
[url "ssh://[email protected]/"] | |
insteadOf = https://github.com/ | |
EOF | |
# Add includeIf for the repository in the Git config | |
cat >> "$GIT_CONFIG_FILE" <<EOF | |
[includeIf "hasconfig:remote.*.url:**/$REPO_NAME"] | |
path = $REPO_GIT_CONFIG | |
[includeIf "hasconfig:remote.*.url:**/$REPO_NAME.git"] | |
path = $REPO_GIT_CONFIG | |
EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment