Skip to content

Instantly share code, notes, and snippets.

@Helw150
Created July 18, 2017 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Helw150/43a63143f187c1268c569434f54c1c7e to your computer and use it in GitHub Desktop.
Save Helw150/43a63143f187c1268c569434f54c1c7e to your computer and use it in GitHub Desktop.
Some more human controls for boto3
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