Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skip the termination of ec2_stop instances #764

Merged
merged 1 commit into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pls add also comment why we comment out this part, so we will know the reason.
"Comment out termination code to reduce the risk of unintended terminations"

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

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
Loading