Created
March 4, 2022 04:21
-
-
Save shaikkhajaibrahim/e09a3d5b2e51112dedd971276dfc6f75 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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