Skip to content

Instantly share code, notes, and snippets.

@eduardosilva
Last active November 7, 2023 13:54
Show Gist options
  • Save eduardosilva/4f77346f7fb3ecd915f5e085ff9549a3 to your computer and use it in GitHub Desktop.
Save eduardosilva/4f77346f7fb3ecd915f5e085ff9549a3 to your computer and use it in GitHub Desktop.
GCloud scripts
#!/usr/bin/env bash
#-------------------------------------------------------------
# Title: GCP Computer Instance Query Executor
# Description: This is a script template that follows some
# best practices for shell scripting. It includes features
# such as named parameters (required or optional), date and
# time handling, logging, colored output, and error handling.
# Author: Eduardo Silva
#
# RECOMMENDATIONS:
# NOT use command arguments abbreviations (Ex.: sed -e / sed -expression)
# OPTIONAL send useless output to (Ex.: command > /dev/null 2>&1)
#-------------------------------------------------------------
# FAULT CONFIGURATION
set -Eeuo pipefail
trap cleanup SIGINT SIGTERM ERR EXIT
# MAGIC VARIABLES
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
__file_name="$(basename "$__file")"
__base="$(basename "${__file}" .sh)"
#-------------------------------------------------------------
# MAING FUNCTION
#-------------------------------------------------------------
main() {
gcloud projects list --format='value(project_id)' | while read -r PROJECT_ID; do
echo "CURRENT PROJECT: $PROJECT_ID"
gcloud compute instances list --project "$PROJECT_ID" --filter="$filter" --quiet 2>/dev/null || true
done
}
#-------------------------------------------------------------
# DISPLAY HOW TO USE THE SCRIPT
#-------------------------------------------------------------
usage() {
cat <<EOF
Usage: $(basename "$__file_name") [-h] [-v] [-f] -p param_value arg1 [arg2...]
The script is designed to execute the gcloud compute instances list command
with specified filters across all projects in Google Cloud Platform (GCP). It
provides a convenient way to retrieve and display information about instances
that match the given filters.
Available options:
-h, --help Print this help and exit
-v, --verbose Print script debug info
-f, --filter Filter to apply in the compute instances
EOF
exit
}
#-------------------------------------------------------------
# EXECUTED WHEN THE SCRIPT IS FINISHED
#-------------------------------------------------------------
cleanup() {
trap - SIGINT SIGTERM ERR EXIT
# script cleanup here
}
#-------------------------------------------------------------
# SET COLORS CONFIGURATION
#-------------------------------------------------------------
setup_colors() {
if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
NOFORMAT='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' BLUE='\033[0;34m' PURPLE='\033[0;35m' CYAN='\033[0;36m' YELLOW='\033[1;33m'
else
NOFORMAT='' RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW=''
fi
}
#-------------------------------------------------------------
# PRINT MESSAGES
# EXAMPLES:
# msg "${RED}Read parameters:${NOFORMAT}"
# msg "- flag: ${flag}"
# msg "- param: ${param}"
# msg "- arguments: ${args[*]-}"
#-------------------------------------------------------------
msg() {
echo >&2 -e "${1-}"
}
#-------------------------------------------------------------
# GET DATE AND TIME
#-------------------------------------------------------------
now(){
date +%F-%T
}
#-------------------------------------------------------------
# GET DATE
#-------------------------------------------------------------
today(){
date -I
}
#-------------------------------------------------------------
# INFO MESSAGE
#-------------------------------------------------------------
info(){
msg "${BLUE}${__file_name} | $(now) - INFO: ${1-} ${NOFORMAT}"
}
#-------------------------------------------------------------
# LOG MESSAGE
#-------------------------------------------------------------
log(){
msg "${YELLOW}${__file_name} | $(now) - LOG: ${1-} ${NOFORMAT}"
}
#-------------------------------------------------------------
# ERROR MESSAGE
#-------------------------------------------------------------
error(){
msg "${RED}${__file_name} | $(now) - ERROR: ${1-} ${NOFORMAT}"
}
#-------------------------------------------------------------
# FINISH EXECUTION
#-------------------------------------------------------------
die() {
local msg=$1
local code=${2-1} # default exit status 1
msg "$msg"
exit "$code"
}
#-------------------------------------------------------------
# PARSE SCRIPT PARAMETERS
#-------------------------------------------------------------
parse_params() {
# default values of variables set from params
filter=''
while :; do
case "${1-}" in
-h | --help) usage ;;
-v | --verbose) set -x ;;
--no-color) NO_COLOR=1 ;;
-f | --filter) # example named parameter
filter="${2-}"
shift
;;
-?*) die "Unknown option: $1" ;;
*) break ;;
esac
shift
done
args=("$@")
# check required params and arguments
[[ -z "${filter-}" ]] && die "Missing required parameter: filter"
return 0
}
parse_params "$@"
setup_colors
main "$@"
#!/bin/bash
# Function to display script usage
function usage {
echo "Usage: $0 -f <filter>"
echo " -f, --filter <filter> Filter for gcloud compute instances list command"
exit 1
}
# Parse command-line options
while getopts "f:-:" opt; do
case $opt in
f)
filter="$OPTARG"
;;
-)
case $OPTARG in
filter)
filter="$2"
shift 2
;;
*)
usage
;;
esac
;;
*)
usage
;;
esac
done
# Check if the filter argument is provided
if [[ -z $filter ]]; then
echo "Filter argument is required."
usage
fi
# clear-snapshots
gcloud compute snapshots list --project <project-id> | awk -v col=1 '{print $col}' | xargs -I % -P 10 gcloud compute snapshots delete % --project <project-id> --quiet
# instances without service account
./query-executor.sh -f "name~^redishot- AND NOT serviceAccounts: * AND status=RUNNING" | tee intermediate.txt && grep '^redishot' intermediate.txt | sed 's/ \+/\t/g' | column -s $'\t' -t > output.txt
# inventory query
gcloud asset search-all-resources --scope <organization-id> --asset-types compute.googleapis.com/Instance --query displayName:mongolu | grep display
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment