Skip to content

Instantly share code, notes, and snippets.

@drhema
Last active December 12, 2024 19:22
Show Gist options
  • Save drhema/0681ee772f5190b8ddde9355dfa3c539 to your computer and use it in GitHub Desktop.
Save drhema/0681ee772f5190b8ddde9355dfa3c539 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Ensure the script is run as root or with sudo
if [ "$(id -u)" != "0" ]; then
echo "Please run this script as root (sudo)."
exit 1
fi
read -sp "Enter the desired Redis password: " REDIS_PASS
echo
# 1. Stop and purge any existing Redis installation
systemctl stop redis-server || true
apt purge redis-server redis-tools -y
apt autoremove -y
# 2. Reinstall Redis
apt update
apt install redis-server -y
# At this point, Redis should be installed with default config.
# Check if it starts in its default form:
systemctl restart redis-server
if ! systemctl is-active --quiet redis-server; then
echo "Redis failed to start with default configuration."
echo "Check 'systemctl status redis-server' and 'journalctl -xeu redis-server.service' for details."
exit 1
fi
echo "Redis started successfully with default configuration."
# 3. Now that Redis starts successfully, make minimal config changes:
REDIS_CONF="/etc/redis/redis.conf"
# Set a password
# If requirepass is commented by default, uncomment it:
sed -i 's/^# requirepass .*/requirepass '"$REDIS_PASS"'/' $REDIS_CONF
# If not found, append:
grep -q "^requirepass" $REDIS_CONF || echo "requirepass $REDIS_PASS" >> $REDIS_CONF
# Bind to all interfaces
sed -i 's/^bind .*/bind 0.0.0.0/' $REDIS_CONF
# Disable protected mode
sed -i 's/^protected-mode .*/protected-mode no/' $REDIS_CONF
# No need to alter supervised or daemonize since the package defaults should be correct
# Maxmemory settings can be added if needed:
# echo "maxmemory 256mb" >> $REDIS_CONF
# echo "maxmemory-policy allkeys-lru" >> $REDIS_CONF
# 4. Restart Redis to apply changes
systemctl restart redis-server
if systemctl is-active --quiet redis-server; then
echo "Redis installation and configuration completed successfully."
echo
echo "To test the connection from your local machine:"
echo "1. Replace YOUR_SERVER_IP with the IP address of your server."
echo "2. Use the password you just chose."
echo
echo "Testing commands:"
echo "redis-cli -h YOUR_SERVER_IP -p 6379 -a $REDIS_PASS ping"
echo
echo "Expected output: PONG"
else
echo "Redis failed to start after configuration changes."
echo "Check 'systemctl status redis-server' and 'journalctl -xeu redis-server.service' for details."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment