Skip to content

Instantly share code, notes, and snippets.

@kat47
Created April 15, 2022 14:07
Show Gist options
  • Save kat47/f217d5bd642db645dfd0cd8bdaa27def to your computer and use it in GitHub Desktop.
Save kat47/f217d5bd642db645dfd0cd8bdaa27def to your computer and use it in GitHub Desktop.
Python script to stop all running instances in a region (AWS)
import boto3
ec2 = boto3.client('ec2')
response = ec2.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
if instance["State"]["Name"] == "running":
print("Stopping instance: " + instance["InstanceId"])
ec2.stop_instances(InstanceIds=[instance["InstanceId"]])
print("Instance stopped: " + instance["InstanceId"])
else:
print("Instance is already stopped: " + instance["InstanceId"])
print("Script completed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment