Skip to content

Instantly share code, notes, and snippets.

@lu911
Created February 15, 2016 03:08
Show Gist options
  • Save lu911/38c83a4253f9399b12b7 to your computer and use it in GitHub Desktop.
Save lu911/38c83a4253f9399b12b7 to your computer and use it in GitHub Desktop.
Fabric Deploy Flask AutoScaling
import boto3
import time
timestamp = int(time.time())
session = boto3.Session(
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=region_name
)
ec2_client = session.client('ec2', region_name=region_name)
as_client = session.client('autoscaling', region_name=region_name)
# Get AutoScaling Group
as_group_name = u'AutoScaling GROUP Name'
res = as_client.describe_auto_scaling_groups(AutoScalingGroupNames=[as_group_name])
old_launch_config_name = res['AutoScalingGroups'][0]['LaunchConfigurationName']
target_instance_id = None
for instance in res['AutoScalingGroups'][0]['Instances']:
if instance['ProtectedFromScaleIn']:
target_instance_id = instance['InstanceId']
break
# Get AutoScaling Launch Configuration
res = as_client.describe_launch_configurations(LaunchConfigurationNames=[old_launch_config_name])
old_launch_config = res['LaunchConfigurations'][0]
old_image_id = old_launch_config['ImageId']
new_launch_config_name = u'ServiceName-elbas-%d' % timestamp
kwargs = dict(
LaunchConfigurationName=new_launch_config_name,
KeyName=old_launch_config['KeyName'],
SecurityGroups=old_launch_config['SecurityGroups'],
InstanceType=old_launch_config['InstanceType'],
BlockDeviceMappings=old_launch_config['BlockDeviceMappings'],
InstanceMonitoring=old_launch_config['InstanceMonitoring'],
EbsOptimized=old_launch_config['EbsOptimized']
)
# Create New AMI
print "Creating EC2 AMI from EC2 Instance: %s" % target_instance_id
res = ec2_client.create_image(
InstanceId=target_instance_id,
Name=u'ServiceName-elbas-%d' % timestamp,
NoReboot=False
)
new_image_id = res['ImageId']
# Create New Launch Configuration
kwargs['ImageId'] = new_image_id
print "Creating an EC2 Launch Configuration for AMI: %s" % new_image_id
as_client.create_launch_configuration(**kwargs)
# Update AutoScaling Group
print "Attaching Launch Configuration to AutoScale Group"
as_client.update_auto_scaling_group(
AutoScalingGroupName=as_group_name,
LaunchConfigurationName=new_launch_config_name
)
# Delete Old AMI and Launch Configuration
print "Deleting old launch configuration: %s" % old_launch_config_name
as_client.delete_launch_configuration(LaunchConfigurationName=old_launch_config_name)
print "Deleting old AMI: %s" % old_image_id
ec2_client.deregister_image(ImageId=old_image_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment