Created
October 2, 2018 15:48
-
-
Save chloegrace94/4822b61d9f0f475ab6b211bfa96a6eb8 to your computer and use it in GitHub Desktop.
Tag EC2 and RDS instances to reserve them
This file contains hidden or 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
| # Instance tagging function | |
| def instance_tagger(action_value, resource_type, instance_id_or_arn, instance_name, user_id): | |
| # Slack users | |
| # cyoung = @cyoung | |
| # user_2 = @user_2 | |
| owner_dict = { | |
| "cyoung" : "xxxxxxxxx", | |
| "user_2" : "zzzzzzzzz" | |
| } | |
| Reserved_by = (list(owner_dict.keys())[list(owner_dict.values()).index(user_id)]) | |
| logger.info("\nTagging with Reserved_by : " + str(Reserved_by)) | |
| # Calculate date-time values | |
| nowdatetime = datetime.now(timezone.utc) | |
| Reserved_until = nowdatetime + timedelta(hours=(float(action_value)*24)) | |
| logger.info("\n Tagging with Reserved_until : " + str(Reserved_until)) | |
| try: | |
| #Add tag EC2 | |
| if (resource_type).upper() == 'EC2': | |
| client = boto3.client('ec2') | |
| # Is instance still running? | |
| response = client.create_tags( | |
| Resources=[ | |
| instance_id_or_arn, | |
| ], | |
| Tags=[ | |
| { | |
| 'Key': 'Reserved_until', | |
| 'Value': str(Reserved_until), | |
| }, | |
| { | |
| 'Key': 'Reserved_by', | |
| 'Value': str(Reserved_by), | |
| }, | |
| ], | |
| ) | |
| # Reserve RDS with tag | |
| elif (resource_type).upper() == 'RDS': | |
| client = boto3.client('rds') | |
| # Is instance still running? | |
| response = client.describe_db_instances( | |
| DBInstanceIdentifier=instance_id_or_arn, | |
| ) | |
| if response['DBInstances'][0]['DBInstanceStatus'] != 'stopped': | |
| response = client.add_tags_to_resource( | |
| ResourceName=instance_id_or_arn, | |
| Tags=[ | |
| { | |
| 'Key': 'Reserved_until', | |
| 'Value': str(Reserved_until) | |
| }, | |
| { | |
| 'Key': 'Reserved_by', | |
| 'Value': str(Reserved_by), | |
| }, | |
| ] | |
| ) | |
| else: | |
| logger.error('Error: %s' % str(err)) | |
| message = (":x: Sorry your instance *" + instance_name + "* cannot be reserved as it is no longer running") | |
| return(message) | |
| # Confirmation message | |
| if action_value == '1': | |
| message = ":heavy_check_mark: Your instance *" + str(instance_name) + "* has been reserved for *" + action_value + "* day" | |
| else: | |
| message = ":heavy_check_mark: Your instance *" + str(instance_name) + "* has been reserved for *" + action_value + "* days" | |
| except Exception as err: | |
| logger.error('Error: %s' % str(err)) | |
| message = (":x: Sorry your instance *" + instance_name + "* cannot be reserved at this time") | |
| return(message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment