ellefc
ellefc

Reputation: 273

What gcloud command would list all the compute instances (for all gcp projects) with a network tag that contains a specific string?

I have put together the code below to find all resources with a network tag that contains -allowaccess however it doesn't seem to work...

for i in $(gcloud projects list | awk NR>1); do gcloud compute instances list --filter="tags.items:-allowaccess --project=$i; done

Any ideas?

Upvotes: 3

Views: 4585

Answers (3)

Antonio Thomacelli
Antonio Thomacelli

Reputation: 108

I think the code self explain :)

# indice of .csv
echo "project;machine;region;family;value1;value2;value3;value4;value5" >> export.csv

# loop projects
for p in $(gcloud projects list | awk '{print $1}' | awk 'NR>1')
do
    # loop values of instance
    for i in $(gcloud compute instances list --project=${p} | grep -v "TERMINATED" | grep -v "NAME")
    do
        if [ "${i}" == "RUNNING" ]
        then
            echo ${instance}
            X=0
        elif [[ $X -eq 0 ]]
        then
            echo -n ${i}
            echo -n ";"
            echo -n ${i}
            echo -n ";"
            X=$((X+1))
        else
            echo -n ${i}
            echo -n ";"
            X=$((X+1))
        fi
    done
done >> export.csv

# remove wrong ;
sed -i 's/,;/ /g' export.csv
sed -i 's/;vCPU/ vCPU/g' export.csv
sed -i 's/;GiB/ GiB/g' export.csv

Upvotes: 0

ellefc
ellefc

Reputation: 273

A colleague of mine figured it out...here's the command - hope it's useful to others!

for i in $(gcloud projects list | awk '{print $1}' | awk 'NR>1'); do echo PROJECT: $i && echo "--" && gcloud compute instances list --project=$i --filter="(tags.items:allowaccess)" && echo ""; done

For each project, this outputs each VM with a network tag that contains the text 'allow access'

Upvotes: 2

Martin Zeitler
Martin Zeitler

Reputation: 76859

Try something alike --filter="label:(*allowaccess)" or --filter="labels.*allowaccess:*", because these are generally instance labels. See gcloud topic filters.

Upvotes: 0

Related Questions