Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if python script is running on an aws instance

I'm trying to set up a python logger to send error emails when it logs an error iff the instance has a tag set. I then quickly run into the problem of local dev computers that aren't on aws. Is there an easy and fast way to check if the script is being run on aws?

I was loading the instance data with:

import boto.utils
from boto.ec2.connection import EC2Connection
metadata = boto.utils.get_instance_metadata()
conn = EC2Connection()
instance = conn.get_only_instances(instance_ids=metadata['instance-id'])[0]

I can of course use a timeout on get_instance_metadata, but there is then a tension between now long to make developers wait vs the possibility of not sending an error email in production.

Can anyone think of a nice solution?

like image 397
TristanMatthews Avatar asked Apr 11 '15 01:04

TristanMatthews


People also ask

How do I know if python script is running in the background?

I usually use ps -fA | grep python to see what processes are running. The CMD will show you what python scripts you have running, although it won't give you the directory of the script. Save this answer.

Can I run a Python script on AWS?

Run a Python script from GitHubOpen the AWS Systems Manager console at https://console.aws.amazon.com/systems-manager/ . In the navigation pane, choose Run Command. If the AWS Systems Manager home page opens first, choose the menu icon ( ) to open the navigation pane, and then choose Run Command. Choose Run command.


2 Answers

Similar to @cgseller, assuming python3, one could do something like:

from urllib.request import urlopen

def is_ec2_instance():
    """Check if an instance is running on AWS."""
    result = False
    meta = 'http://169.254.169.254/latest/meta-data/public-ipv4'
    try:
        result = urlopen(meta).status == 200
    except ConnectionError:
        return result
    return result
like image 194
sedeh Avatar answered Oct 06 '22 20:10

sedeh


Alternatively, you can check if your environment contains any AWS environmental variables:

is_aws = True if os.environ.get("AWS_DEFAULT_REGION") else False

I chose to inspect if my user name is an ec2 instance: (Not a great solution, but it works)

my_user = os.environ.get("USER")
is_aws = True if "ec2" in my_user else False
like image 24
Yaakov Bressler Avatar answered Oct 06 '22 21:10

Yaakov Bressler