MiniDiscovery/scripts/deregister_service.sh

89 lines
2.4 KiB
Bash

#!/bin/bash
# Script to deregister a service from MiniDiscovery service
# Default values
BASE_URL="http://localhost:8500"
SERVICE_ID=""
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-t|--token)
API_TOKEN="$2"
shift 2
;;
-u|--url)
BASE_URL="$2"
shift 2
;;
-i|--id)
SERVICE_ID="$2"
shift 2
;;
--last)
# Try to read the service ID from the file created during registration
if [ -f .last_registered_service_id ]; then
SERVICE_ID=$(cat .last_registered_service_id)
else
echo "Error: No previously registered service ID found."
exit 1
fi
shift
;;
-h|--help)
echo "Usage: $0 -t API_TOKEN (-i SERVICE_ID | --last) [options]"
echo "Options:"
echo " -t, --token TOKEN API token for authentication (required)"
echo " -u, --url URL Base URL of the API (default: $BASE_URL)"
echo " -i, --id SERVICE_ID Service ID to deregister (required unless --last is used)"
echo " --last Deregister the last registered service"
echo " -h, --help Show this help message"
exit 0
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
done
# Check if API token is provided
if [ -z "$API_TOKEN" ]; then
echo "Error: API token is required"
echo "Use -t or --token to provide the API token"
exit 1
fi
# Check if service ID is provided
if [ -z "$SERVICE_ID" ]; then
echo "Error: Service ID is required"
echo "Use -i or --id to provide the service ID, or --last to use the last registered service"
exit 1
fi
# Make API request to deregister the service
echo "Deregistering service ID: $SERVICE_ID"
RESPONSE=$(curl -s -X PUT \
-H "X-API-Token: $API_TOKEN" \
-H "Accept: application/json" \
"${BASE_URL}/v1/agent/service/deregister/${SERVICE_ID}")
# Check if the request was successful
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X PUT \
-H "X-API-Token: $API_TOKEN" \
-H "Accept: application/json" \
"${BASE_URL}/v1/agent/service/deregister/${SERVICE_ID}")
if [ "$HTTP_CODE" -eq 200 ]; then
echo "Deregistration successful!"
# Remove the stored service ID if --last was used
if [ -f .last_registered_service_id ] && [ "$(cat .last_registered_service_id)" = "$SERVICE_ID" ]; then
rm .last_registered_service_id
fi
else
echo "Deregistration failed. HTTP code: $HTTP_CODE"
echo "Response: $RESPONSE"
exit 1
fi