Kevin Meyer
Kevin Meyer

Reputation: 2966

How can I tell if my machine is an EC2 instance or not?

I need a Ruby function that will tell me whether or not this machine is an EC2 instance, 100% of the time, even when DNS is broken on our EC2 instances.

The function that we were using was:

def is_ec2?
  require 'socket'
  Socket::gethostbyname('instance-data.ec2.internal.')
  true
rescue
  false
end

Except that when the DNS broke, every EC2 machine thought that it WASN'T an EC2 machine, and bad things happened, like the production machine deleting its own SSL certs and replacing them with the local develepment box's certs..

In Python, we're using:

@memoized
def is_ec2():
    # This is a 99% check to avoid the need to wait for the timeout. 
    # Our VM's have this file.  Our dev VM's don't.  
    if not os.path.isfile('/sys/hypervisor/uuid'):
        return False

    try:
        result = boto.utils.get_instance_metadata()
        if result == {}:
            return False
        return True
    except Exception:
        return False

Except for using wget -q -O - http://169.254.169.254/latest/meta-data instead of boto.utils.get_instance_metadata(), would that work?

Upvotes: 0

Views: 557

Answers (1)

pguardiario
pguardiario

Reputation: 54984

Just put that in your hosts file and you won't have to worry about DNS.

But really, doesn't it make more sense to use an ENV var?

Upvotes: 1

Related Questions