Skip to content

Instantly share code, notes, and snippets.

@lsemenenko
Created October 11, 2024 12:50
Show Gist options
  • Save lsemenenko/025791f7ec3503e3e49960dc686c652f to your computer and use it in GitHub Desktop.
Save lsemenenko/025791f7ec3503e3e49960dc686c652f to your computer and use it in GitHub Desktop.
List Vultr servers via API
#!/bin/bash
# Check if API key is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <VULTR_API_KEY>"
exit 1
fi
# Vultr API key from command-line argument
VULTR_API_KEY="$1"
# API endpoint
API_ENDPOINT="https://api.vultr.com/v2/instances"
# Make the API request and store the response
response=$(curl -s \
-H "Authorization: Bearer ${VULTR_API_KEY}" \
-H "Content-Type: application/json" \
"${API_ENDPOINT}")
# Check if the request was successful
if [[ "${response}" != *'"instances":'* ]]; then
echo "Error: Unable to fetch server list. Check your API key and try again."
exit 1
fi
# Parse and display the active servers
echo "Active Servers:"
echo "${response}" | grep -o '{[^}]*}' | while read -r instance; do
if [[ "${instance}" == *'"status":"active"'* ]]; then
id=$(echo "${instance}" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
label=$(echo "${instance}" | grep -o '"label":"[^"]*' | cut -d'"' -f4)
ip=$(echo "${instance}" | grep -o '"main_ip":"[^"]*' | cut -d'"' -f4)
echo "${id}: ${label} (${ip})"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment