Skip to content

Commit

Permalink
Skip the termination of ec2_stop instances
Browse files Browse the repository at this point in the history
  • Loading branch information
athiruma committed Apr 26, 2024
1 parent 1aa6962 commit b2d9ec9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 28 deletions.
19 changes: 10 additions & 9 deletions cloud_governance/policy/aws/ec2_stop.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,16 @@ def __fetch_stop_instance(self, instance_days: int, delete_instance_days: int, s
tag_specifications = [{'ResourceType': 'image', 'Tags': tags}]
if sign == ge:
tag_specifications.append({'ResourceType': 'snapshot', 'Tags': tags})
try:
ami_id = self._ec2_client.create_image(InstanceId=instance_id, Name=self._get_tag_name_from_tags(tags=tags), TagSpecifications=tag_specifications)['ImageId']
delta_charge = self.get_ebs_cost(resource=block_device_mappings[instance_id], resource_type='ec2', resource_hours=(self.DAILY_HOURS * (self.DELETE_INSTANCE_DAYS-self.DAYS_TO_NOTIFY_ADMINS)))
stop_cost = self.get_ebs_cost(resource=block_device_mappings[instance_id], resource_type='ec2', resource_hours=(self.DAILY_HOURS * days))
self.__trigger_mail(tags=tags, stopped_time=stopped_time, days=days, resource_id=instance_id, image_id=ami_id, ec2_type=ec2_types[instance_id], instance_id=instance_id, message_type='delete', stop_cost=stop_cost, delta_charge=delta_charge)
self._ec2_client.terminate_instances(InstanceIds=[instance_id])
logger.info(f'Deleted the instance: {instance_id}')
except Exception as err:
logger.info(err)
# Commenting out termination code to reduce the risk of unintended terminations
# try:
# ami_id = self._ec2_client.create_image(InstanceId=instance_id, Name=self._get_tag_name_from_tags(tags=tags), TagSpecifications=tag_specifications)['ImageId']
# delta_charge = self.get_ebs_cost(resource=block_device_mappings[instance_id], resource_type='ec2', resource_hours=(self.DAILY_HOURS * (self.DELETE_INSTANCE_DAYS-self.DAYS_TO_NOTIFY_ADMINS)))
# stop_cost = self.get_ebs_cost(resource=block_device_mappings[instance_id], resource_type='ec2', resource_hours=(self.DAILY_HOURS * days))
# self.__trigger_mail(tags=tags, stopped_time=stopped_time, days=days, resource_id=instance_id, image_id=ami_id, ec2_type=ec2_types[instance_id], instance_id=instance_id, message_type='delete', stop_cost=stop_cost, delta_charge=delta_charge)
# self._ec2_client.terminate_instances(InstanceIds=[instance_id])
# logger.info(f'Deleted the instance: {instance_id}')
# except Exception as err:
# logger.info(err)
return stopped_instances

def __trigger_mail(self, tags: list, stopped_time: str, resource_id: str, days: int, image_id: str = '', ec2_type: str = '', instance_id: str = '', **kwargs):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@
os.environ['AWS_DEFAULT_REGION'] = 'us-east-2'


@mock_cloudtrail
@mock_ec2
def test_ec2_stop():
"""
This method tests, termination of stopped instance more than 30 days and create an image, snapshot
@return:
"""
ec2_client = boto3.client('ec2', region_name=os.environ.get('AWS_DEFAULT_REGION'))
default_ami_id = 'ami-03cf127a'
tags = [{'Key': 'Name', 'Value': 'CloudGovernanceTestInstance'}, {'Key': 'User', 'Value': 'cloud-governance'}]
instance_id = ec2_client.run_instances(ImageId=default_ami_id, InstanceType='t2.micro', MaxCount=1, MinCount=1, TagSpecifications=[{'ResourceType': 'instance', 'Tags': tags}])['Instances'][0].get('InstanceId')
ec2_client.stop_instances(InstanceIds=[instance_id])
ec2_stop = EC2Stop()
ec2_stop.set_dryrun(value='no')
ec2_stop._EC2Stop__fetch_stop_instance(sign=le, instance_days=1, delete_instance_days=0)
amis = ec2_client.describe_images(Owners=['self'])['Images']
snapshot_id = amis[0].get('BlockDeviceMappings')[0].get('Ebs').get('SnapshotId')
snapshots = ec2_client.describe_snapshots(OwnerIds=['self'], SnapshotIds=[snapshot_id])['Snapshots']
assert len(snapshots) == len(amis)
# @mock_cloudtrail
# @mock_ec2
# def test_ec2_stop():
# """
# This method tests, termination of stopped instance more than 30 days and create an image, snapshot
# @return:
# """
# ec2_client = boto3.client('ec2', region_name=os.environ.get('AWS_DEFAULT_REGION'))
# default_ami_id = 'ami-03cf127a'
# tags = [{'Key': 'Name', 'Value': 'CloudGovernanceTestInstance'}, {'Key': 'User', 'Value': 'cloud-governance'}]
# instance_id = ec2_client.run_instances(ImageId=default_ami_id, InstanceType='t2.micro', MaxCount=1, MinCount=1, TagSpecifications=[{'ResourceType': 'instance', 'Tags': tags}])['Instances'][0].get('InstanceId')
# ec2_client.stop_instances(InstanceIds=[instance_id])
# ec2_stop = EC2Stop()
# ec2_stop.set_dryrun(value='no')
# ec2_stop._EC2Stop__fetch_stop_instance(sign=le, instance_days=1, delete_instance_days=0)
# amis = ec2_client.describe_images(Owners=['self'])['Images']
# snapshot_id = amis[0].get('BlockDeviceMappings')[0].get('Ebs').get('SnapshotId')
# snapshots = ec2_client.describe_snapshots(OwnerIds=['self'], SnapshotIds=[snapshot_id])['Snapshots']
# assert len(snapshots) == len(amis)


@mock_cloudtrail
Expand Down

0 comments on commit b2d9ec9

Please sign in to comment.