Last active
January 11, 2018 22:42
-
-
Save maxmcd/7fe3fb97483aef0aafc479057a25ac80 to your computer and use it in GitHub Desktop.
Terminate all stopped instances in all AWS regions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
China region has been removed, I don't have access to that.