Skip to content

Instantly share code, notes, and snippets.

@developerck
Created August 30, 2021 17:50
Show Gist options
  • Save developerck/82cb2a2250f6b35254a44e1f50628c47 to your computer and use it in GitHub Desktop.
Save developerck/82cb2a2250f6b35254a44e1f50628c47 to your computer and use it in GitHub Desktop.
aws resize ec2 through lambda
import boto3
import json
import os
import logging
region = ''
region = os.environ['region'];
if not region :
logger.error('Missing region');
raise
ec2 = boto3.client('ec2', region_name=region)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
stopped=0;
logger.info("Event Object");
logger.info(json.dumps(event));
instance_id = event['detail']['instance-id'];
instance_type = event['detail']['instance-type'];
logger.info("Instance Id : %s", instance_id);
logger.info("Instance Type : %s", instance_type);
## check for ec2 resource state
ec2 = boto3.client('ec2', region);
response = ec2.describe_instance_status(InstanceIds=[instance_id]);
logger.info("Instance Detail");
print(logger.info(json. dumps(response)));
try :
instance_state = response['InstanceStatuses'][0]['InstanceState']['Name'];
logger.info("Instance State : %s", instance_state);
### do the resize if instance is running , no for stopeed instance
if instance_state == 'running':
ec2.stop_instances(InstanceIds=[instance_id]);
stopped =1;
waiter=ec2.get_waiter('instance_stopped');
waiter.wait(InstanceIds=[instance_id]);
print ("Stopped : %s", instance_id);
## change the instance type
ec2.modify_instance_attribute(InstanceId=instance_id, Attribute='instanceType', Value=instance_type)
print (instance_id, " resized to ", instance_type);
## modified then start the instance
logger.info("Starting Instance ");
## start instance
responses = ec2.start_instances(
InstanceIds=[instance_id]
);
logger.info("Instance Started.");
else :
logger.info("Instance Not running");
raise
except IndexError:
logger.info("Instance is not running state ");
return 0;
except :
## check if we stopped the instance
if stopped :
## starting the instance which we stopped
responses = ec2.start_instances(
InstanceIds=[instance_id]
);
return 1;
event :
{
"detail": {
"instance-id": "i-06eef1aa6eba41194",
"instance-type": "t2.small"
}
}
environment vairable :
region
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment