eran
eran

Reputation: 15156

Find out if the current machine is on aws in python

I have a python script that runs on aws machines, as well as on other machines. The functionality of the script depends on whether or not it is on AWS.

Is there a way to programmatically discover whether or not it runs on AWS? (maybe using boto?)

Upvotes: 2

Views: 311

Answers (4)

Roy2012
Roy2012

Reputation: 12543

I tried some of the above, and when not running on Amazon I had troubles accessing 169.254.169.254. Maybe it has something to do with the fact I'm outside the US.

In any case, here's a piece of code that worked for me:

def running_on_amazon():
  import urllib2
  import socket

  # I'm using curlmyip.com, but there are other websites that provide the same service 
  ip_finder_addr = "http://curlmyip.com" 
  f = urllib2.urlopen(ip_finder_addr)
  my_ip = f.read(100).strip()
  host_addr = socket.gethostbyaddr(my_ip)

  my_public_name = host_addr[0]
  amazon = (my_public_name.find("aws") >=0 )
  return amazon # returns a boolean value. 

Upvotes: 0

garnaat
garnaat

Reputation: 45926

If you want to do that strictly using boto, you could do:

import boto.utils
md = boto.utils.get_instance_metadata(timeout=.1, num_retries=0)

The timeout specifies the how long the HTTP client will wait for a response before timing out. The num_retries parameter controls how many times the client will retry the request before giving up and returning and empty dictionary.

Upvotes: 3

eran
eran

Reputation: 15156

I found a way, using:

try:
    instance_id_resp = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
    is_on_aws = True
except requests.exceptions.ConnectionError as e:
    is_on_awas = False

Upvotes: 0

sd1sd1
sd1sd1

Reputation: 1048

you can easily use the AWS SDK and check for instance id. beside of that, you can check the aws ip ranges - check out this link https://forums.aws.amazon.com/ann.jspa?annID=1701

Upvotes: 1

Related Questions