#!/usr/bin/env bash # Configuration HOSTS_FILE="$HOME/portainer/agent_hosts.txt" AGENT_CONTAINER_NAME="portainer_agent" AGENT_IMAGE="portainer/agent:latest" # Adjust these according to how you originally ran the agent: DOCKER_RUN_CMD=( docker run -d \ --name "${AGENT_CONTAINER_NAME}" \ --restart=always \ -p 9001:9001 \ -v /var/run/docker.sock:/var/run/docker.sock \ -v /var/lib/docker/volumes:/var/lib/docker/volumes \ "${AGENT_IMAGE}" ) if [[ ! -f "$HOSTS_FILE" ]]; then echo "Hosts file not found: $HOSTS_FILE" exit 1 fi while read -r HOST; do [[ -z "$HOST" || "$HOST" =~ ^# ]] && continue echo "==> Checking host: $HOST" ssh "$HOST" bash -s << 'REMOTE_EOF' AGENT_CONTAINER_NAME="portainer_agent" AGENT_IMAGE="portainer/agent:latest" # Function to echo with host prefix log() { echo "[$(hostname)] $*" } if ! command -v docker &>/dev/null; then log "docker not installed or not in PATH" exit 1 fi # Is container present? if docker ps -a --format '{{.Names}}' | grep -wq "$AGENT_CONTAINER_NAME"; then # Is it running? if docker ps --format '{{.Names}}' | grep -wq "$AGENT_CONTAINER_NAME"; then log "Agent container '$AGENT_CONTAINER_NAME' is already running" exit 0 else log "Agent container exists but is stopped, starting..." if docker start "$AGENT_CONTAINER_NAME"; then log "Agent container started" exit 0 else log "Failed to start agent container, will try to recreate" docker rm -f "$AGENT_CONTAINER_NAME" || true fi fi else log "Agent container '$AGENT_CONTAINER_NAME' not found, creating..." fi # Recreate container with the same options you use everywhere log "Running new agent container..." docker run -d \ --name "\$AGENT_CONTAINER_NAME" \ --restart=always \ -p 9001:9001 \ -v /var/run/docker.sock:/var/run/docker.sock \ -v /var/lib/docker/volumes:/var/lib/docker/volumes \ "\$AGENT_IMAGE" RET=\$? if [[ \$RET -eq 0 ]]; then log "Agent container created and started" else log "Failed to create agent container (exit \$RET)" fi REMOTE_EOF done < "$HOSTS_FILE"