Skip to content

Commit 4ee6d9e

Browse files
committed
Devops: add pull-env.sh helper to sync env
1 parent 607ed93 commit 4ee6d9e

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Unreleased (develop)
44

55
- added: push-env-key.sh script for updating env configs on remote servers
6+
- added: pull-env.sh helper that pulls remote env.json and backs up local changes before overwriting
67

78
## 4.45.0 (staging)
89

scripts/pull-env.sh

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#!/bin/bash
2+
set -euo pipefail
3+
4+
REMOTE_HOST="jack"
5+
REMOTE_FILE="env.json"
6+
LOCAL_ENV="env.json"
7+
REMOTE_BASE='\$HOME/jenkins-files'
8+
9+
usage() {
10+
cat <<EOF
11+
Pull the remote env.json from $REMOTE_HOST and update the local copy.
12+
13+
Usage: $(basename "$0") [-f FOLDER]
14+
15+
-f FOLDER Remote folder under ~/jenkins-files (default: master)
16+
-h Show this help message
17+
EOF
18+
exit 1
19+
}
20+
21+
TARGET_FOLDER=""
22+
while getopts "f:h" opt; do
23+
case $opt in
24+
f) TARGET_FOLDER="$OPTARG" ;;
25+
h) usage ;;
26+
*) usage ;;
27+
esac
28+
done
29+
shift $((OPTIND - 1))
30+
31+
TARGET_FOLDER="${TARGET_FOLDER:-master}"
32+
TARGET_FOLDER="${TARGET_FOLDER#/}"
33+
TARGET_FOLDER="${TARGET_FOLDER%/}"
34+
[ -z "$TARGET_FOLDER" ] && TARGET_FOLDER="master"
35+
36+
REMOTE_REPO="$REMOTE_BASE/$TARGET_FOLDER"
37+
38+
REMOTE_TMP="$(mktemp)"
39+
trap 'rm -f "$REMOTE_TMP"' EXIT
40+
41+
echo "Pulling latest env.json from $REMOTE_HOST ($TARGET_FOLDER)..."
42+
ssh "$REMOTE_HOST" "cd \"$(eval echo $REMOTE_REPO)\" && git pull --ff-only" >&2
43+
scp -q "$REMOTE_HOST:$(ssh $REMOTE_HOST eval echo $REMOTE_REPO)/$REMOTE_FILE" "$REMOTE_TMP"
44+
45+
backup_local_env() {
46+
local base="${LOCAL_ENV}.bak"
47+
local candidate="$base"
48+
if [ -e "$candidate" ]; then
49+
local counter=1
50+
while [ -e "${base}-${counter}" ]; do
51+
counter=$((counter + 1))
52+
done
53+
candidate="${base}-${counter}"
54+
fi
55+
56+
cp "$LOCAL_ENV" "$candidate"
57+
echo "$candidate"
58+
}
59+
60+
if [ ! -f "$LOCAL_ENV" ]; then
61+
echo "No local $LOCAL_ENV found; creating from remote."
62+
cp "$REMOTE_TMP" "$LOCAL_ENV"
63+
exit 0
64+
fi
65+
66+
if diff -q "$LOCAL_ENV" "$REMOTE_TMP" >/dev/null 2>&1; then
67+
echo "Local $LOCAL_ENV already matches remote; nothing to do."
68+
exit 0
69+
fi
70+
71+
BACKUP_PATH=$(backup_local_env)
72+
echo "Backed up local $LOCAL_ENV to $BACKUP_PATH"
73+
74+
cp "$REMOTE_TMP" "$LOCAL_ENV"
75+
echo "Updated $LOCAL_ENV with contents from $REMOTE_HOST/$TARGET_FOLDER."

0 commit comments

Comments
 (0)