Created
March 11, 2018 22:06
-
-
Save boneyard93501/4f11d412c2ffa3c972487cb6efe7f5e9 to your computer and use it in GitHub Desktop.
ec2 instance toggle
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
note to self: toggle ec2 instance by one of two instance types using boto3 | |
!/usr/bin/env python3 | |
# -*- coding: utf8 -*- | |
import os, sys | |
import datetime | |
import boto3 | |
THIS_DIR = os.path.dirname(sys.argv[0]) | |
LOG_PATH = os.path.join(THIS_DIR,'odb_content_instance_change.txt') | |
INSTANCE_ID = 'i-XXX' | |
TYPE_OPTIONS = ('t2.medium', 't2.large') | |
def toggle(instance_id: str = INSTANCE_ID) -> None: | |
msg = f'instance change for {instance_id}, {datetime.datetime.utcnow()}' | |
try: | |
ec2 = boto3.client('ec2') | |
descr = ec2.describe_instance_attribute(Attribute='instanceType',InstanceId=instance_id) | |
current_type = descr['InstanceType']['Value'] | |
new_type = TYPE_OPTIONS[0] | |
if current_type==TYPE_OPTIONS[0]: | |
new_type = TYPE_OPTIONS[1] | |
msg += f' from {current_type} to {new_type}' | |
ec2.stop_instances(InstanceIds=[instance_id]) | |
waiter = ec2.get_waiter('instance_stopped') | |
waiter.wait(InstanceIds=[instance_id]) | |
ec2.modify_instance_attribute(InstanceId=instance_id, | |
Attribute='instanceType', | |
Value=new_type) | |
ec2.start_instances(InstanceIds=[instance_id]) | |
except Exception as e: | |
msg += f' failed : {e}' | |
msg += '\n' | |
with open(LOG_PATH, 'a') as fd: | |
fd.write(msg) | |
if __name__=='__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment