Skip to content

Instantly share code, notes, and snippets.

@mrsimonbennett
Created January 25, 2025 08:34
Show Gist options
  • Save mrsimonbennett/e720bde3e31b4ca6f2d92623dcd3dbf7 to your computer and use it in GitHub Desktop.
Save mrsimonbennett/e720bde3e31b4ca6f2d92623dcd3dbf7 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Define the custom Docker network
CUSTOM_NETWORK="pcktly_bridge"
echo "Current time: $(date)"
# Ensure the custom network exists
if ! docker network ls | grep -q "$CUSTOM_NETWORK"; then
echo "Custom network $CUSTOM_NETWORK does not exist. Creating it now..."
docker network create --driver bridge "$CUSTOM_NETWORK"
if [ $? -ne 0 ]; then
echo "Failed to create custom network $CUSTOM_NETWORK. Exiting."
exit 1
fi
echo "Custom network $CUSTOM_NETWORK created successfully."
fi
while true
do
# Get all running ECS containers
CONTAINERS=$(docker ps -q --filter "label=com.amazonaws.ecs.task-arn")
if [ -z "$CONTAINERS" ]; then
echo "No ECS containers are currently running."
exit 0
fi
# Loop through the containers
for CONTAINER in $CONTAINERS; do
# Extract the task definition family from container labels
TASK_FAMILY=$(docker inspect -f '{{ index .Config.Labels "com.amazonaws.ecs.container-name" }}' "$CONTAINER")
# Fallback to container ID if task family label is missing
if [ -z "$TASK_FAMILY" ]; then
echo "Task definition family not found for container $CONTAINER. Using container ID as alias."
TASK_FAMILY="$CONTAINER"
fi
# Check if the container is already connected to the custom network
if ! docker network inspect "$CUSTOM_NETWORK" | grep -q "$CONTAINER"; then
echo "Attaching container $CONTAINER to $CUSTOM_NETWORK with alias $TASK_FAMILY..."
docker network connect --alias "$TASK_FAMILY" "$CUSTOM_NETWORK" "$CONTAINER"
if [ $? -eq 0 ]; then
echo "Container $CONTAINER successfully connected to $CUSTOM_NETWORK with alias $TASK_FAMILY."
else
echo "Failed to connect container $CONTAINER to $CUSTOM_NETWORK."
fi
fi
done
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment