#!/bin/bash # # Portainer Agent Deployment Script for Docker Swarm # Usage: bash deploy_portainer_agent.sh # set -euo pipefail log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; } log "Checking Docker Swarm status..." if ! docker info --format '{{.Swarm.LocalNodeState}}' | grep -q "active"; then log "ERROR: This node is not part of a Docker Swarm." exit 1 fi if ! docker info --format '{{.Swarm.ControlAvailable}}' | grep -q "true"; then log "ERROR: This script must be run on a Swarm MANAGER node." exit 1 fi log "Creating overlay network for Portainer Agent..." if ! docker network ls | grep -q "portainer_agent_network"; then docker network create --driver overlay portainer_agent_network else log "Network 'portainer_agent_network' already exists, skipping." fi log "Deploying Portainer Agent as a global Swarm service..." if docker service ls | grep -q "portainer_agent"; then log "Agent service already exists. Updating to latest image..." docker service update --image portainer/agent:latest portainer_agent else docker service create \ --name portainer_agent \ --network portainer_agent_network \ --publish mode=host,target=9001,published=9001 \ -e AGENT_CLUSTER_ADDR=tasks.portainer_agent \ --mode global \ --mount type=bind,src=//var/run/docker.sock,dst=/var/run/docker.sock \ --mount type=bind,src=//var/lib/docker/volumes,dst=/var/lib/docker/volumes \ --mount type=bind,src=//,dst=/host \ portainer/agent:latest fi log "=== Portainer Agent Deployment Complete ===" log "The agent is now deploying to all nodes in your Swarm." log "To manage your Swarm:" log "1. Open your Portainer Server UI." log "2. Go to 'Environments' -> 'Add environment'." log "3. Select 'Docker Swarm' and click 'Start Wizard'." log "4. Choose 'Agent' and enter the Environment address: $(hostname -I | awk '{print $1}'):9001" log "5. Click 'Connect'."