Skip to content

Instantly share code, notes, and snippets.

@aculich
Created April 13, 2024 09:08
Show Gist options
  • Save aculich/5a08350733a2b93fc279ea3db1fc27c2 to your computer and use it in GitHub Desktop.
Save aculich/5a08350733a2b93fc279ea3db1fc27c2 to your computer and use it in GitHub Desktop.
#!/bin/bash
# turn GCP (Google Cloud Platform) metadata key/values into shell environment variables
# Function to fetch metadata and set as environment variable
fetch_and_export() {
local path=$1
local value=$(curl "http://metadata.google.internal/computeMetadata/v1/${path}" -H "Metadata-Flavor: Google" --silent)
if [ $? -eq 0 ] && [ ! -z "$value" ]; then
# Convert metadata keys to uppercase and replace invalid characters for shell variable names
local varname=$(echo $path | tr '[:lower:]/-' '[:upper:]__')
# Special handling for the instance zone to extract only the last part
if [ "$path" == "instance/zone" ]; then
value=$(basename "$value")
fi
# Remove 'PROJECT__' prefix if present
varname=$(echo $varname | sed 's/^PROJECT_PROJECT_/PROJECT_/')
varname=$(echo $varname | sed 's/^PROJECT_NUMERIC_PROJECT_ID/PROJECT_NUMERIC_ID/')
# Export the environment variable
export "$varname"="$value"
#echo "Exported $varname"
fi
}
# Metadata paths to fetch and set as environment variables
METADATA_PATHS=(
"instance/cpu-platform"
"instance/disks"
"instance/id"
"instance/machine-type"
"instance/name"
"instance/scheduling/automatic-restart"
"instance/scheduling/on-host-maintenance"
"instance/scheduling/preemptible"
"instance/service-accounts/default/aliases"
"instance/service-accounts/default/email"
"instance/service-accounts/default/scopes"
"instance/tags"
"instance/zone"
"project/numeric-project-id"
"project/project-id"
)
# Loop through the metadata paths and set environment variables
for path in "${METADATA_PATHS[@]}"; do
fetch_and_export $path
done
# Now, print all environment variables that were set
printenv | grep '^INSTANCE_' || echo "No instance-specific environment variables were set."
printenv | grep '^PROJECT_' || echo "No project-specific environment variables were set."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment