Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juliofalbo/af917d08e01be6b16fbc2f626d8b2d20 to your computer and use it in GitHub Desktop.
Save juliofalbo/af917d08e01be6b16fbc2f626d8b2d20 to your computer and use it in GitHub Desktop.
addPrometheusServiceDiscoveryService 'my_image_name' 8080 'my_container_prefix_' myservice
#
# Function responsible to add specific instances to a prometheus service discovery file
#
function addPrometheusServiceDiscoveryService {
IMAGE_NAME=$1
NUM_INSTANCES=$(docker ps | grep -c "$IMAGE_NAME")
PORT=$2
CONTAINER_NAME=$3
SERVICE_NAME=$4
TARGETS=''
for ((i=1; i<NUM_INSTANCES+1; i++))
do
CONTAINER_EXPOSED_PORT=$(docker port "$CONTAINER_NAME$i" "$PORT" | cut -d':' -f 2)
TARGETS+="\"host.docker.internal:$CONTAINER_EXPOSED_PORT\", "
done
if [ "$NUM_INSTANCES" -gt 0 ]
then
TARGETS=${TARGETS::${#TARGETS}-2}
if [ -f "$HOME/targets.json" ] && grep -q "\"job\": \"instances_" "$HOME/targets.json";
then
CONTENT="\ \ \{ \n \ \ \ \"targets\": [ $TARGETS ]\, \n \ \ \ \"labels\": \{ \n \ \ \ \ \ \"env\": \"local\", \n \ \ \ \ \ \"job\": \"instances_$SERVICE_NAME\" \n \ \ \ \} \n \ \},";
gsed -i "\$i $CONTENT" "$HOME"/targets.json
else
echo "[
{
\"targets\": [ $TARGETS ],
\"labels\": {
\"env\": \"local\",
\"job\": \"instances_$SERVICE_NAME\"
}
},
]" > "$HOME"/targets.json
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment