Created
February 14, 2024 15:25
-
-
Save Rohithzr/9de6fc28495b82997b9391e4b4e6781f to your computer and use it in GitHub Desktop.
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 | |
# File to replace | |
CONFIG_FILE="/etc/containerd/config.toml" | |
# Ensure MIRROR_EP is set | |
if [ -z "$MIRROR_EP" ]; then | |
echo "MIRROR_EP is not set. Exiting." | |
exit 1 | |
fi | |
# Backup the file | |
cp "$CONFIG_FILE" "$CONFIG_FILE.bak" | |
orig_line=$(grep "sandbox_image" "$CONFIG_FILE") | |
spaces=$(echo "$orig_line" | sed 's/[^ ].*//' | awk '{print length}') | |
# Read the entire content of the file into a variable, with newline characters preserved | |
content=$(<"$CONFIG_FILE") | |
mirror_ep_line=" endpoint = [\"$MIRROR_EP\"]" | |
echo "Setting the registry mirror to $MIRROR_EP." | |
# Function to check if any mirror settings exist | |
check_mirror_existence() { | |
grep -q ".registry.mirrors." "$CONFIG_FILE" | |
} | |
# Only proceed if the mirror settings do not exist | |
if ! check_mirror_existence; then | |
echo "Adding new registry mirror settings." | |
new_content=$(echo "$content" | awk -v orig_line="$orig_line" -v mirror_ep_line="$mirror_ep_line" -v spaces="$spaces" -v ORS="" '{ | |
if (index($0, "sandbox_image") > 0) { | |
indent = sprintf("%*s", spaces, ""); | |
print orig_line "\n"; | |
print indent "# Add registry mirror\n"; | |
print indent "[plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors.\"docker.io\"]\n"; | |
print indent mirror_ep_line "\n"; | |
} else { | |
print $0 "\n"; | |
} | |
}') | |
# Write the new content back to the file | |
echo "$new_content" > "$CONFIG_FILE" | |
else | |
echo "Updating existing registry mirror URL." | |
# Replace existing mirror host with the new host if different | |
sed -i.bak -E "s|endpoint = \[\"http(s)?://[^\"]+\"\]|endpoint = [\"$MIRROR_EP\"]|" "$CONFIG_FILE" | |
fi | |
# Restart containerd to apply changes | |
# Find the PID of containerd | |
pid=$(ps aux | grep '/usr/bin/containerd' | grep -v 'grep' | grep -v 'shim' | awk '{print $2}') | |
# Check if the PID was found | |
if [ -z "$pid" ]; then | |
echo "containerd process not found." | |
else | |
# Send SIGHUP to containerd | |
kill -s HUP $pid | |
echo "Sent SIGHUP to containerd with PID $pid." | |
fi | |
# After the main task is completed | |
if [ $? -eq 0 ]; then | |
echo "Script completed successfully." | |
else | |
echo "Script encountered an error." | |
fi | |
tail -f /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment