Created
July 18, 2017 18:41
-
-
Save Helw150/43a63143f187c1268c569434f54c1c7e to your computer and use it in GitHub Desktop.
Some more human controls for boto3
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 get_id_from_name(name): | |
description = [instance for r in response['Reservations'] for instance in r['Instances'] for tag in instance['Tags'] if tag['Key'] == 'Name' if tag['Value'] == name] | |
return description['InstanceId'] | |
def start_instance_by_name(name): | |
ec2 = boto3.client('ec2') | |
instance_id = get_id_from_name(name) | |
# Do a dryrun first to verify permissions | |
try: | |
ec2.start_instances(InstanceIds=[instance_id], DryRun=True) | |
except ClientError as e: | |
if 'DryRunOperation' not in str(e): | |
raise | |
# Dry run succeeded, run start_instances without dryrun | |
try: | |
response = ec2.start_instances(InstanceIds=[instance_id], DryRun=False) | |
print(response) | |
except ClientError as e: | |
print(e) | |
def stop_instances_by_name(name): | |
ec2 = boto3.client('ec2') | |
instance_id = get_id_from_name(name) | |
# Do a dryrun first to verify permissions | |
try: | |
ec2.stop_instances(InstanceIds=[instance_id], DryRun=True) | |
except ClientError as e: | |
if 'DryRunOperation' not in str(e): | |
raise | |
# Dry run succeeded, call stop_instances witout dryrun | |
try: | |
response = ec2.stop_instances(InstanceIds=[instance_id], DryRun=False) | |
print(response) | |
except ClientError as e: | |
print(e) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment