Skip to content

Instantly share code, notes, and snippets.

@sdkks
Last active February 23, 2022 14:55
Show Gist options
  • Save sdkks/7f104b9671973afcf430ebb9a5e35098 to your computer and use it in GitHub Desktop.
Save sdkks/7f104b9671973afcf430ebb9a5e35098 to your computer and use it in GitHub Desktop.
Stop AWS instances with matching tags
#!/usr/bin/env python3
# Assumes you have Python 3 and boto3 installed in your [virtual]env
# Assumes we are taking positional parameters (this script could be longer with argparse)
# Assumes you have AWS_PROFILE and AWS_DEFAULT_REGION set and credentials are valid and not expired at ~/.aws/credentials
import boto3
import json
from sys import argv, exit
if len(argv) != 3:
print("This script takes exactly two arguments, tag name and value")
exit(1)
client = boto3.client("ec2")
def filter_hosts(tag_name, tag_value):
response = client.describe_instances(
Filters=[
{
"Name": f"tag:{tag_name}",
"Values": [tag_value],
},
{
"Name": "instance-state-name",
"Values": ["running"],
},
],
MaxResults=1000,
)
try:
instance_data = []
for reservation in response["Reservations"]:
instance_data.append(reservation["Instances"][0])
return instance_data
except IndexError:
print("No matches for given tags")
return None
def stop_instances(instances):
for instance in instances:
instance_id = instance["InstanceId"]
private_ip_address = instance["PrivateIpAddress"]
image_id = instance["ImageId"]
try:
client.stop_instances(
InstanceIds=[
instance_id,
]
)
print(
json.dumps(
{
"instance_id": instance_id,
"private_ip_address": private_ip_address,
"image_id": image_id,
}
)
)
except:
print(f"Stopping instance {instance_id} has failed")
def main(tag_name, tag_value):
instances = filter_hosts(tag_name, tag_value)
stop_instances(instances)
if __name__ == "__main__":
tag_name = argv[1]
tag_value = argv[2]
main(tag_name, tag_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment