Last active
October 21, 2020 16:48
-
-
Save ffturan/ca0f15345f579146a167eb72b52e03ee to your computer and use it in GitHub Desktop.
Use an existing tag on AWS EC2 instance/s to add/delete new/old tags
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
#!/usr/bin/env python3 | |
# | |
# Use an existing tag on AWS EC2 instance/s to add/delete new/old tags. | |
# | |
# Usage: ./ec2-instance-tagger.py <aws-profile> <aws-region> <existing-tag-key> <existing-tag-value> <target-tag-key> <target-tag-value> <action> | |
# | |
# I've 3 EC2 instances already tagged with Temp:True , adding new tag Zone:2 | |
# ./ec2-instance-tagger.py myawsprofile us-east-1 Temp True Zone 2 add | |
# Expected output: | |
#+---------------------+------+-------+--------+ | |
#| ID | TAG | VALUE | ACTION | | |
#+---------------------+------+-------+--------+ | |
#| i-0559c5798de2c.... | Zone | 2 | add | | |
#| i-01c4a3c613c90.... | Zone | 2 | add | | |
#| i-067e9b541d01e.... | Zone | 2 | add | | |
#+---------------------+------+-------+--------+ | |
# | |
# I've 3 EC2 instances already tagged with Temp:True , deleting Zone:2 tag | |
# ./ec2-instance-tagger.py myawsprofile us-east-1 Temp True Zone 2 delete | |
# Expected output: | |
#+---------------------+------+-------+--------+ | |
#| ID | TAG | VALUE | ACTION | | |
#+---------------------+------+-------+--------+ | |
#| i-0559c5798de2c.... | Zone | 2 | delete | | |
#| i-01c4a3c613c90.... | Zone | 2 | delete | | |
#| i-067e9b541d01e.... | Zone | 2 | delete | | |
#+---------------------+------+-------+--------+ | |
import boto3 | |
import sys | |
from botocore.exceptions import ClientError | |
from prettytable import PrettyTable | |
def connect_aws(vProfile, vRegion, vService): | |
try: | |
boto3.setup_default_session(profile_name=vProfile, region_name=vRegion) | |
worker = boto3.client(vService) | |
return worker | |
except ClientError as e: | |
print(e) | |
def check_args(): | |
if len(sys.argv) < 7: | |
print( | |
f'Usage: {sys.argv[0]} aws-profile aws-region existing-tag-key existing-tag-value target-tag-key target-tag-value action') | |
exit() | |
def ec2_add_tag(vWorker, vInstanceId, vTargetTagKey, vTargetTagValue): | |
try: | |
response = vWorker.create_tags(Resources=[vInstanceId, ], Tags=[ | |
{'Key': vTargetTagKey, 'Value': vTargetTagValue, }, ], ) | |
except ClientError as e: | |
print(e) | |
return response | |
def ec2_delete_tag(vWorker, vInstanceId, vTargetTagKey, vTargetTagValue): | |
try: | |
response = vWorker.delete_tags(Resources=[vInstanceId, ], Tags=[ | |
{'Key': vTargetTagKey, 'Value': vTargetTagValue, }, ], ) | |
except ClientError as e: | |
print(e) | |
return response | |
def ec2_tagger(vWorker, vAction): | |
# Pretty Table prepare | |
vCuteTable = PrettyTable() | |
# Empty List | |
vWorkerList = [] | |
# Get Instance List | |
try: | |
response = vWorker.describe_instances( | |
Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'stopped']}, ]) | |
except ClientError as e: | |
print(e) | |
if vAction.lower() == 'list': | |
for reservation in response["Reservations"]: | |
for instance in reservation["Instances"]: | |
vIdHolder = instance["InstanceId"] | |
for item in instance["Tags"]: | |
if item['Key'] == gExistingTagKey and item['Value'] == gExistingTagValue: | |
vWorkerList.append( | |
(vIdHolder, item['Key'], item['Value'], vAction.lower())) | |
elif vAction.lower() == 'add': | |
for reservation in response["Reservations"]: | |
for instance in reservation["Instances"]: | |
vIdHolder = instance["InstanceId"] | |
for item in instance["Tags"]: | |
if item['Key'] == gExistingTagKey and item['Value'] == gExistingTagValue: | |
ec2_add_tag( | |
vWorker, vIdHolder, gTargetTagKey, gTargetTagValue) | |
vWorkerList.append( | |
(vIdHolder, gTargetTagKey, gTargetTagValue, vAction.lower())) | |
elif vAction.lower() == 'delete': | |
for reservation in response["Reservations"]: | |
for instance in reservation["Instances"]: | |
vIdHolder = instance["InstanceId"] | |
for item in instance["Tags"]: | |
if item['Key'] == gExistingTagKey and item['Value'] == gExistingTagValue: | |
ec2_delete_tag( | |
vWorker, vIdHolder, gTargetTagKey, gTargetTagValue) | |
vWorkerList.append( | |
(vIdHolder, gTargetTagKey, gTargetTagValue, vAction.lower())) | |
else: | |
print(f'I do not know what to do !!!') | |
exit() | |
vCuteTable.field_names = ["ID", "TAG", "VALUE", "ACTION"] | |
for item in vWorkerList: | |
vCuteTable.add_row([item[0], item[1], item[2], item[3]]) | |
return vCuteTable | |
# | |
# MAIN STARTS HERE | |
# | |
if __name__ == '__main__': | |
# Check number of arguments | |
check_args() | |
# Set vars | |
gProfile = sys.argv[1] | |
gRegion = sys.argv[2] | |
gExistingTagKey = sys.argv[3] | |
gExistingTagValue = sys.argv[4] | |
gTargetTagKey = sys.argv[5] | |
gTargetTagValue = sys.argv[6] | |
gAction = sys.argv[7] | |
# Connect to AWS | |
worker_ec2 = connect_aws(gProfile, gRegion, 'ec2') | |
result = ec2_tagger(worker_ec2, gAction) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment