Skip to content

Instantly share code, notes, and snippets.

@maxmcd
Last active January 11, 2018 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxmcd/7fe3fb97483aef0aafc479057a25ac80 to your computer and use it in GitHub Desktop.
Save maxmcd/7fe3fb97483aef0aafc479057a25ac80 to your computer and use it in GitHub Desktop.
Terminate all stopped instances in all AWS regions
import boto3
regions = [
'us-east-2',
'us-east-1',
'us-west-1',
'us-west-2',
'ap-south-1',
'ap-northeast-2',
'ap-southeast-1',
'ap-southeast-2',
'ap-northeast-1',
#'cn-north-1,
'ca-central-1',
'eu-central-1',
'eu-west-1',
'eu-west-2',
'eu-west-3',
'sa-east-1',
]
for region in regions:
ec2 = boto3.client(
'ec2',
aws_access_key_id='no',
aws_secret_access_key='no',
region_name=region)
response = ec2.describe_instances()
instances = []
if response['Reservations']:
instances = response['Reservations'][0]['Instances']
for image in instances:
if image['State']['Name'] == 'stopped':
response = ec2.modify_instance_attribute(
InstanceId=image['InstanceId'],
DisableApiTermination={'Value': False},
)
print(response)
instance_ids = [
instance['InstanceId'] for instance in instances
if instance['State']['Name'] == 'stopped'
]
print(instance_ids)
if instance_ids:
response = ec2.terminate_instances(InstanceIds=instance_ids)
print(response)
@maxmcd
Copy link
Author

maxmcd commented Jan 11, 2018

China region has been removed, I don't have access to that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment