I wanted to keep Crowdsec updated from both an image perspective and from the hub updates/upgrades. I used ChatGPT to help create this script, which I think accomplishes all of this, and I thought I would share in case it would be helpful for anyone else.
-
Create script in home directory
sudo nano update_crowdsec.sh -
Copy the following code and replace the USERNAME with your own username:
#!/bin/bash
COMPOSE_DIR="/home/USERNAME"
LOG_FILE="/tmp/crowdsec_update.log"
CONTAINER_NAME="crowdsec"
IMAGE_NAME="crowdsecurity/crowdsec"
DOCKER="/usr/bin/docker"
COMPOSE="$DOCKER compose"
GREP="/bin/grep"
cd "$COMPOSE_DIR" || exit 1
echo "$(date): Checking for CrowdSec image updates..." > "$LOG_FILE"
# Step 1: Pull the latest image
$DOCKER pull "$IMAGE_NAME" >> "$LOG_FILE" 2>&1
# Step 2: Get current and latest image IDs
CURRENT_IMAGE_ID=$($DOCKER inspect --format='{{.Image}}' "$CONTAINER_NAME" 2>/dev/null)
LATEST_IMAGE_ID=$($DOCKER inspect --format='{{.Id}}' "$IMAGE_NAME" 2>/dev/null)
# Step 3: Recreate container if image changed
if [ "$CURRENT_IMAGE_ID" != "$LATEST_IMAGE_ID" ]; then
echo "$(date): New image detected. Recreating only the CrowdSec container..." >> "$LOG_FILE"
$DOCKER stop "$CONTAINER_NAME" >> "$LOG_FILE" 2>&1
$DOCKER rm "$CONTAINER_NAME" >> "$LOG_FILE" 2>&1
$COMPOSE up -d "$CONTAINER_NAME" >> "$LOG_FILE" 2>&1
else
echo "$(date): No new image. Container not recreated." >> "$LOG_FILE"
fi
# Step 4: Run hub update and upgrade
echo "$(date): Running cscli hub update/upgrade..." >> "$LOG_FILE"
$DOCKER exec "$CONTAINER_NAME" cscli hub update >> "$LOG_FILE" 2>&1
$DOCKER exec "$CONTAINER_NAME" cscli hub upgrade >> "$LOG_FILE" 2>&1
# Step 5: Restart if hub changes applied
if $GREP -qE "Updated|Downloading|Upgrade" "$LOG_FILE"; then
echo "$(date): Hub updates applied. Restarting container to activate changes..." >> "$LOG_FILE"
$DOCKER restart "$CONTAINER_NAME" >> "$LOG_FILE" 2>&1
else
echo "$(date): No hub updates. No second restart needed." >> "$LOG_FILE"
fi
echo "$(date): CrowdSec update script complete." >> "$LOG_FILE"
-
Make script executable:
sudo chmod +x update_crowdsec.sh -
Setup root crontab
sudo crontab -e -
Add 2am updates (change USERNAME to your username):
0 2 * * * /home/USERNAME/update_crowdsec.sh
You can run the script manually and check the temp log using:
cat /tmp/crowdsec_update.log