Skip to content

Instantly share code, notes, and snippets.

@shaikkhajaibrahim
Created March 4, 2022 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shaikkhajaibrahim/e09a3d5b2e51112dedd971276dfc6f75 to your computer and use it in GitHub Desktop.
Save shaikkhajaibrahim/e09a3d5b2e51112dedd971276dfc6f75 to your computer and use it in GitHub Desktop.
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