Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import boto3
def start_instances_by_tag(region, tag_name, tag_value):
"""
This method will find the instances in a region
"""
ec2 = boto3.client('ec2', region_name=region)
response = ec2.describe_instances(Filters=[
{
'Name': f'tag:{tag_name}',
'Values': [tag_value]
}
])
instances_found = response['Reservations'][0]['Instances']
print(f"found {len(instances_found)} instances")
#for instance in response['Reservations'][0]['Instances']:
# ec2.start_instances(InstanceIds=[instance['InstanceId']])
instance_ids = [ instance['InstanceId'] for instance in response['Reservations'][0]['Instances']]
response = ec2.start_instances(InstanceIds=instance_ids)
print(response)
def stop_instances_by_tag(region, tag_name, tag_value):
"""
This method will find the instances in a region
"""
ec2 = boto3.client('ec2', region_name=region)
response = ec2.describe_instances(Filters=[
{
'Name': f'tag:{tag_name}',
'Values': [tag_value]
}
])
instances_found = response['Reservations'][0]['Instances']
print(f"found {len(instances_found)} instances")
#for instance in response['Reservations'][0]['Instances']:
# ec2.start_instances(InstanceIds=[instance['InstanceId']])
instance_ids = [ instance['InstanceId'] for instance in response['Reservations'][0]['Instances']]
response = ec2.stop_instances(InstanceIds=instance_ids)
print(response)
def lambda_handler(event, context):
start_instances_by_tag('us-west-2', 'env', 'qa')
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment