Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check in bash if I am in a Google Compute Engine instance

I would like to check in a bash script whether I am in a Google Compute Engine instance or in my Linux laptop. How can I differentiate them?

like image 821
poiuytrez Avatar asked Jan 08 '23 18:01

poiuytrez


1 Answers

See Detect if a VM is running in Compute Engine at GCE documentation:

$ curl metadata.google.internal -i
HTTP/1.1 200 OK
Metadata-Flavor: Google
Content-Type: application/text
Date: Tue, 23 Nov 2021 01:27:16 GMT
Server: Metadata Server for VM
Content-Length: 22
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN

0.1/
computeMetadata/

You can use the internal IP (169.254.169.254) for the metadata server instead.

The documentation (link above) also provides an alternative that uses an operating system tool:

sudo dmidecode -s system-product-name | grep "Google Compute Engine"
case $? in
(0) echo On a GCE instance;;
(*) echo Not a GCE instance;;
esac

or

$ dmesg | grep -q "BIOS Google"
case $? in
(0) echo On a GCE instance;;
(*) echo Not a GCE instance;;
esac

Checking for relevant strings as "google", "virt" or "kvm" in dmesg output can provide hints too.

like image 97
Antxon Avatar answered Jan 25 '23 20:01

Antxon