how to check if a python script is running in an ec2?

0

are there any environment variables that i can check if exists , while running my python script in an aws ec2 or a sagemaker instance ? something like this ...

import os 

aws_environment = os.environ.get('AWS..') 

질문됨 3달 전195회 조회
3개 답변
1

Hello.

How about writing code to get instance metadata?
I tried translating the commands described in the document below into python.
You can check the EC2 instance ID by running the Python below.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html

import requests

def get_ec2_metadata():
    token_url = "http://169.254.169.254/latest/api/token"
    meta_data_instance_id = "http://169.254.169.254/latest/meta-data/instance-id"

    headers = {
        "X-aws-ec2-metadata-token-ttl-seconds": "21600"
    }
    response = requests.put(token_url, headers=headers)
    token = response.text

    headers = {
        "X-aws-ec2-metadata-token": token
    }
    response = requests.get(meta_data_instance_id, headers=headers)
    metadata = response.text

    return metadata

metadata = get_ec2_metadata()
print(metadata)
profile picture
전문가
답변함 3달 전
profile pictureAWS
전문가
검토됨 3달 전
0

Hi,

Sagemaker API has a specific Python API to retrieve its default environment variables. It's sagemaker.environment_variables.retrieve_default()

See documentation: https://sagemaker.readthedocs.io/en/v2.78.0/api/utility/environment_variables.html

Best,

Didier

profile pictureAWS
전문가
답변함 3달 전
  • thanks, aren't there any env variables that are set in the environment, when a instance spins up in sagemaker , that i can check if exists?

0

You can check for the presence of the instance metadata service as it won't respond it you're not running on EC2:

import requests

try:
    requests.get('http://169.254.169.254/', timeout=2)
except OSError:
    print('Not running on EC2')
else:
    print('Running on EC2')
profile pictureAWS
전문가
답변함 3달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠