Skip to content

Instantly share code, notes, and snippets.

@adhorn
Last active September 23, 2019 00:03
Show Gist options
  • Save adhorn/dbb0350dcd2cbf6301538a977e3910f6 to your computer and use it in GitHub Desktop.
Save adhorn/dbb0350dcd2cbf6301538a977e3910f6 to your computer and use it in GitHub Desktop.
Example script to stop random ec2 instance in a particular AZ if that instance tag matches the input
import boto3
import random
REGION = 'eu-west-1'
def stop_random_instance(az, tag_name, tag_value, region=REGION):
'''
>>> stop_random_instance(az="eu-west-1a", tag_name='chaos', tag_value="chaos-ready", region='eu-west-1')
['i-0ddce3c81bc836560']
'''
ec2 = boto3.client("ec2", region_name=region)
paginator = ec2.get_paginator('describe_instances')
pages = paginator.paginate(
Filters=[
{
"Name": "availability-zone",
"Values": [
az
]
},
{
"Name": "tag:" + tag_name,
"Values": [
tag_value
]
}
]
)
instance_list = []
for page in pages:
for reservation in page['Reservations']:
for instance in reservation['Instances']:
instance_list.append(instance['InstanceId'])
print("Going to stop any of these instances", instance_list)
selected_instance = random.choice(instance_list)
print("Randomly selected", selected_instance)
response = ec2.stop_instances(InstanceIds=[selected_instance])
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment