user12690225
user12690225

Reputation:

How to check whether if I'm running the code on a GCP / AWS instance?

is there a way to perform a check to indicate on which platform I am? what I mean by that is not that I want to check whether it's Linux or Darwin I mean I need to check whether I am on a cloud instance, I use GCP and AWS so I need some accurate way.

The only answers I found are in some very old post which checks using os.environ() for a SERVER_NAME which I tried and it does not work. I may hardcode a check for my ip address maybe or anything that works only for me but I think there is a clean solution.

Upvotes: 1

Views: 1930

Answers (4)

Sasi Varunan
Sasi Varunan

Reputation: 2864

This might change over years, But around 2022 i use below method to check who is the service provider.

ipinfo provides a json result of server basic details. then you can identify using hostname or org

curl ipinfo.io

"hostname": "x.x.x.x.bc.googleusercontent.com",
"hostname": "ec2-x-x-x-x.compute-1.amazonaws.com"
"org": "x Microsoft Corporation"

Upvotes: 2

John Rotenstein
John Rotenstein

Reputation: 270274

Both AWS and GCP use the same URL for instance metadata: http://169.254.169.254

However, the contents that is returned is different. So, you can use that information to determine whether code is running on a cloud system, and which one.

Upvotes: 0

Tamás Sallai
Tamás Sallai

Reputation: 3365

For a reliable way, I'd do a query for the external IP address (provided that the instance has internet connectivity), such as using https://ifconfig.me/ , then check if the answer is in the the AWS/GCP IP address range (for AWS: https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html, I don't know about GCP).

Upvotes: 1

unbe_ing
unbe_ing

Reputation: 195

As long as the hostnames are set for both hosts, you could get the current hostname of the machine the code is running on by using sockets:

import socket
print(socket.gethostname())

Upvotes: 0

Related Questions