Last active
August 27, 2019 21:53
-
-
Save ratulbasak/0a78cad938c4d6adbc2d0f506891bf42 to your computer and use it in GitHub Desktop.
this will delete an existing ami and creates new ami from a specific instance, creates new instance from newly created ami and attached it to load balancer
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
import boto3 | |
import time | |
region = 'us-east-1' | |
image_name = "image_name" | |
instance_id = "i-0777a5dc8892fbdbb" | |
elb_name = 'elb' | |
instance_type = 't2.micro' | |
instance_tag_name = 'Friendly_Name' | |
AZ_name = 'us-east-1b' | |
SECURITY_GROUP_ID = 'sg-2a45d85c' | |
INSTANCE_SUBNET_ID = 'subnet-65c5ee3f' | |
###################### DELETING IMAGE IF EXISTS #################### | |
#################################################################### | |
client = boto3.client('ec2', region_name=region) | |
print("FINDING AND REPLACING THE EXISTING IMAGE...") | |
response = client.describe_images( | |
Filters=[ | |
{ | |
'Name': 'name', | |
'Values': [ | |
image_name, | |
] | |
}, | |
], | |
Owners=['self'], | |
) | |
print(response) | |
for image in response['Images']: | |
ami_id = image['ImageId'] | |
print("IMAGE_ID: " + ami_id) | |
if ami_id in image['ImageId']: | |
print("DELETING IMAGE") | |
client.deregister_image(ImageId=ami_id) | |
time.sleep(240) | |
########################## CREATING IMAGE ########################### | |
##################################################################### | |
ec2client = boto3.client('ec2', region_name=region) | |
print("CREATING IMAGE FROM INSTANCE " + instance_id) | |
createAMI = ec2client.create_image( | |
InstanceId = instance_id, | |
Name = image_name, | |
Description = image_name, | |
NoReboot = True) | |
imageID = [] | |
imageID.append(createAMI) | |
def getImageId(imageID): | |
for i in imageID: | |
newami = i['ImageId'] | |
return newami | |
newImageId = getImageId(imageID) | |
print("IMAGE_ID: " + newImageId) | |
waiter = ec2client.get_waiter('image_available') ######## WAIT UNTIL IMAGE IS AVAILABLE | |
waiter.wait( | |
Filters=[ | |
{ | |
'Name': 'state', | |
'Values': ['available'] | |
}, | |
], | |
ImageIds=[newImageId], | |
Owners=['self'] | |
) | |
######################### CREATING INSTANCE ######################### | |
##################################################################### | |
ec2=boto3.resource('ec2', region_name=region) | |
print("CREATING INSTANCE FROM THE IMAGE_ID...") | |
instance = ec2.create_instances( | |
ImageId=newImageId, | |
MinCount=1, | |
MaxCount=1, | |
InstanceType=instance_type, | |
KeyName='new-vargin', | |
Monitoring={'Enabled': False}, | |
Placement={'AvailabilityZone': AZ_name, | |
'Tenancy': 'default'}, | |
SecurityGroupIds=[SECURITY_GROUP_ID], | |
SubnetId=INSTANCE_SUBNET_ID, | |
EbsOptimized=False, | |
TagSpecifications=[{'ResourceType': 'instance', | |
'Tags': [{'Key': 'Name', | |
'Value': instance_tag_name}] | |
}], | |
#IamInstanceProfile={'Name': 'your_IAM_role'} | |
) | |
new_instance_id = instance[0].id | |
print("NEW INSTANCE ID " + new_instance_id) | |
ec2_client=boto3.client('ec2', region_name=region) ######## WAIT UNTIL INSTANCE IS AVAILABLE | |
waiter=ec2_client.get_waiter('instance_running') | |
waiter.wait(InstanceIds=[instance[0].instance_id]) | |
############################ CREATING ALARM ########################## | |
##################################################################### | |
cloudwatch = boto3.client('cloudwatch', region_name=region) | |
# Create alarm with actions enabled | |
cloudwatch.put_metric_alarm( | |
AlarmName='Server_LOW_CPU_Utilization', | |
ComparisonOperator='LessThanThreshold', | |
EvaluationPeriods=1, | |
MetricName='CPUUtilization', | |
Namespace='AWS/EC2', | |
Period=300, | |
Statistic='Average', | |
Threshold=30.0, | |
ActionsEnabled=True, | |
AlarmActions=[ | |
'arn:aws:automate:us-east-1:ec2:terminate' | |
], | |
AlarmDescription='Alarm when server CPU exceeds 30%', | |
Dimensions=[ | |
{ | |
'Name': 'InstanceId', | |
'Value': new_instance_id | |
}, | |
], | |
# Unit='Seconds' | |
) | |
########################## ATTATCH TO ELB ########################### | |
##################################################################### | |
print("ATTATCHING CREATED INSTANCE " + new_instance_id + "UNDER ELB " + elb_name) | |
client = boto3.client('elb', region_name=region) | |
response = client.describe_load_balancers( | |
LoadBalancerNames=[elb_name], | |
) | |
#print(response) | |
response = client.register_instances_with_load_balancer( | |
Instances=[ | |
{ | |
'InstanceId': new_instance_id, | |
}, | |
], | |
LoadBalancerName=elb_name, | |
) | |
print(response) | |
print("INSTANCE ATTATCHED...") | |
# ################# ATTATCH TO ALB ###################### | |
# ####################################################### | |
# client = boto3.client('elbv2', region_name=region) | |
# | |
# print("PLACE THE INSTANCE BEHIND THE APPLICATION LOAD BALANCER...") | |
# response = client.register_targets( | |
# TargetGroupArn='TARGET_GROUP_ARN', | |
# Targets=[ | |
# { | |
# 'Id': new_instance_id, | |
# }, | |
# ] | |
# ) | |
# print(response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment