Skip to content

Instantly share code, notes, and snippets.

@DanClarke-io
Created February 18, 2025 16:28
Show Gist options
  • Select an option

  • Save DanClarke-io/9b17af049940ab09e92b9f2bfd9eeee2 to your computer and use it in GitHub Desktop.

Select an option

Save DanClarke-io/9b17af049940ab09e92b9f2bfd9eeee2 to your computer and use it in GitHub Desktop.
Update Portainer edge agent script that pulls (and tempoarily stores) the edge key and edge id and passes it to the new docker container.
#!/bin/bash
# Check if a version argument is provided
if [[ -z "$1" ]]; then
echo "Usage: $0 <portainer_agent_version>"
exit 1
fi
VERSION="$1"
TEMP_FILE="/tmp/portainer_edge_credentials"
# Function to retrieve environment variables from the running container
get_edge_credentials() {
EDGE_ID=$(docker inspect portainer_edge_agent --format '{{ range .Config.Env }}{{ println . }}{{ end }}' | grep -oP '^EDGE_ID=\K.*')
EDGE_KEY=$(docker inspect portainer_edge_agent --format '{{ range .Config.Env }}{{ println . }}{{ end }}' | grep -oP '^EDGE_KEY=\K.*')
# Ensure both values were retrieved
if [[ -n "$EDGE_ID" && -n "$EDGE_KEY" ]]; then
echo "EDGE_ID=$EDGE_ID" > "$TEMP_FILE"
echo "EDGE_KEY=$EDGE_KEY" >> "$TEMP_FILE"
elif [[ -f "$TEMP_FILE" ]]; then
# If retrieval fails, fallback to stored values
echo "Failed to retrieve EDGE_ID/EDGE_KEY from container. Using stored values."
source "$TEMP_FILE"
else
echo "Failed to retrieve EDGE_ID or EDGE_KEY, and no backup exists. Exiting."
exit 1
fi
}
# Get the credentials
get_edge_credentials
echo "Using EDGE_ID: $EDGE_ID"
echo "Using EDGE_KEY: $EDGE_KEY"
echo "Updating Portainer Agent to version $VERSION"
# Stop and remove the existing container
docker stop portainer_edge_agent
docker rm portainer_edge_agent
# Pull and start the specified version
docker run -d \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /var/lib/docker/volumes:/var/lib/docker/volumes \
-v /:/host \
-v portainer_agent_data:/data \
--restart always \
-e EDGE=1 \
-e EDGE_ID="$EDGE_ID" \
-e EDGE_KEY="$EDGE_KEY" \
-e EDGE_INSECURE_POLL=1 \
--name portainer_edge_agent \
portainer/agent:"$VERSION"
# Check if the container started successfully
if [[ "$(docker inspect -f '{{.State.Running}}' portainer_edge_agent 2>/dev/null)" == "true" ]]; then
echo "Portainer Edge Agent updated successfully!"
rm -f "$TEMP_FILE" # Remove stored credentials only if everything works
else
echo "Error: Portainer Edge Agent failed to start. Credentials are saved in $TEMP_FILE for retry."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment