Skip to content

Instantly share code, notes, and snippets.

@tylerneylon
Created March 20, 2023 20:19
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 tylerneylon/8d114d40cd005d75fe60a65b511bad41 to your computer and use it in GitHub Desktop.
Save tylerneylon/8d114d40cd005d75fe60a65b511bad41 to your computer and use it in GitHub Desktop.
A short sweet Python script to simplify starting/stopping a particular ec2 instance
#!/usr/bin/env python3
""" toggle
Usage:
toggle start
toggle getip
toggle stop
"""
# ______________________________________________________________________
# Imports
import sys
import boto3
# ______________________________________________________________________
# Globals
INSTANCE_NAME = 'YOUR_INSTANCE_NAME'
REGION = 'YOUR_REGION'
# ______________________________________________________________________
# Main
if __name__ == '__main__':
if len(sys.argv) < 2:
print(__doc__)
sys.exit(0)
action = sys.argv[1]
if action not in ['start', 'stop', 'getip']:
print(__doc__)
sys.exit(0)
# Create an ec2 client
ec2 = boto3.client(
'ec2',
region_name = REGION
)
# Get a list of instances we might care about.
target_state = 'stopped' if action == 'start' else 'running'
stopped_instances = ec2.describe_instances(
Filters=[ {
'Name': 'instance-state-name',
'Values': [target_state]
} ]
)
instance_id = None
for instance in stopped_instances['Reservations']:
for i in instance['Instances']:
for tag in i['Tags']:
if tag['Key'] == 'Name' and tag['Value'] == INSTANCE_NAME:
instance_id = i['InstanceId']
if action == 'getip':
public_ip = i['PublicIpAddress']
if instance_id is None:
print(f'Ruh-roh, I couldn\'t find the instance_id for', INSTANCE_NAME)
sys.exit(0)
if action == 'start':
ec2.start_instances(InstanceIds=[instance_id])
elif action == 'stop':
ec2.stop_instances(InstanceIds=[instance_id])
else:
print(public_ip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment