Created
December 23, 2020 11:25
-
-
Save rohit-saharan/b24d96723ea52182a2c9fda5ed28c912 to your computer and use it in GitHub Desktop.
Script for resizing an EC2 instance, and restarting it. Prints the new IP at the end.
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
#!/usr/bin/env python3 | |
import boto3 | |
import argparse | |
from time import sleep | |
def getInstanceIP(id): | |
resp = client.describe_instances(InstanceIds=[args.ec2]) | |
try: | |
return resp['Reservations'][0]['Instances'][0]['PublicIpAddress'] | |
except: | |
print("Unable to fetch IP. Please use AWS Console") | |
return "" | |
def getInstanceInfo(id): | |
#first show the instance info. only going to pickup the first instance. | |
resp = client.describe_instances(InstanceIds=[args.ec2]) | |
for res in resp['Reservations'][0]['Instances']: | |
try: | |
if (res['Tags'][0]['Key'] == 'Name'): | |
print("Instance Name: " + res['Tags'][0]['Value']) | |
print("Instance Current Size: " + res['InstanceType']) | |
except: | |
print("some key error") | |
parser = argparse.ArgumentParser() | |
parser.add_argument("ec2", help="ec2 instance id") | |
parser.add_argument("size", help="size to change to") | |
args = parser.parse_args() | |
client = boto3.client('ec2') | |
# Insert your Instance ID here | |
my_instance = args.ec2 | |
#print inst info first | |
getInstanceInfo(my_instance) | |
reply = str(input("Do you want to continue with the operation?(y/[n]):")).lower().strip() | |
if (reply[0] is not 'y'): | |
print("aborting") | |
exit() | |
# Stop the instance | |
print("Stopping existing instance...") | |
client.stop_instances(InstanceIds=[my_instance]) | |
waiter=client.get_waiter('instance_stopped') | |
waiter.wait(InstanceIds=[my_instance]) | |
print("Changing instance type to : " + args.size) | |
# Change the instance type | |
client.modify_instance_attribute(InstanceId=my_instance, Attribute='instanceType', Value=args.size) | |
# Start the instance | |
print("starting instance..") | |
client.start_instances(InstanceIds=[my_instance]) | |
# sleep 10 secs to get ip | |
sleep(10) | |
print("New IP is : " + getInstanceIP(my_instance)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment