Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

amazon ec2 - How to check application runs in AWS EC2 instance

How can I check which platform my app runs, AWS EC2 instance, Azure Role instance and non-cloud system? now I do that like this:

if(isAzure())
{
    //run in Azure role instance
}
else if(isAWS())
{
   //run in AWS EC2 instance
}
else
{
   //run in the non-cloud system
}

//checked whether it runs in AWS EC2 instance or not.
bool isAWS()
{
  string url = "http://instance-data";
  try
  {
     WebRequest req = WebRequest.Create(url);
     req.GetResponse();
     return true;
  }
  catch
  {
     return false;
  }  
}

but I have one problem when my apps runs in the non-cloud system, like local windows system. It got very slowly while executing isAWS() method. the code 'req.GetResponse()' takes a long time. so I want to know how can I to deal with it? please help me! thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The better way to do this would be to make a request to get instance metadata.

From the AWS Documentation:

To view all categories of instance metadata from within a running instance, use the following URI:

http://169.254.169.254/latest/meta-data/

On a Linux instance, you can use a tool such as cURL, or use the GET command, for example:

PROMPT> GET http://169.254.169.254/latest/meta-data/

Here's an example using the Python Boto wrapper:

from boto.utils import get_instance_metadata

m = get_instance_metadata()

if len(m.keys()) > 0:
    print "Running on EC2"

else:
    print "Not running on EC2"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...