Skip to content

Instantly share code, notes, and snippets.

@ilbambino
Created February 5, 2021 13:46
Show Gist options
  • Save ilbambino/a9e7b4288f5add613f8a36a90c7fa9a4 to your computer and use it in GitHub Desktop.
Save ilbambino/a9e7b4288f5add613f8a36a90c7fa9a4 to your computer and use it in GitHub Desktop.
#!/bin/bash
# this script copies iterates the VMs of a GCP project and copies
# the labels of a machine to the disks attached to it
# you can pass a filter (the same as in gcloud command line)
# eg: to exclude some machines with fufu in the name 'name!~.*fufu.*'
if [ $# -eq 0 ]
then
echo "Need to supply project ID"
exit 1
fi
project=$1
filter=""
if [ $# -eq 2 ]
then
echo "Filtering with $2"
filter=" --filter=$2 "
fi
# get VMs and Zones
vmszones=$(gcloud compute instances list --project "${project}" --format="csv[no-heading](name,zone)" ${filter})
# vmszones=$(cat list) # to debug
for entry in $vmszones; do
IFS=','
read -r vm zone <<< "${entry}"
labelsSource=$(gcloud compute instances describe --project "${project}" --zone ${zone} ${vm} --format="csv[no-heading](labels,disks.source)")
read -r labels disks <<< "${labelsSource}"
echo "VM: ${vm} Zone: ${zone} labels: ${labels/;/,}"
IFS=';'
read -a diskA <<< "${disks}"
for disk in ${diskA[@]}; do
echo "${disk##*/}" # to get the name, we strip the last part of the full URL source
gcloud compute disks add-labels "${disk##*/}" --project "${project}" --labels=${labels/;/,} --zone=${zone}
done;
done;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment