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?
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With