import os import boto3 from ec2_metadata import ec2_metadata def stop_instance(): try: ec2_path = r"/home/ec2-user" if os.path.exists(ec2_path): current_ec2_id = ec2_metadata.instance_id region = ec2_metadata.region ec2 = boto3.client('ec2', region_name=region) ec2.stop_instances(instance_ids=[current_ec2_id]) except Exception as e: print(e) os.system("sudo shutdown now -h")