Skip to content

Instantly share code, notes, and snippets.

@willgarcia
Created May 3, 2024 06:07
Show Gist options
  • Save willgarcia/371c9a30ebcf4d6d7a815da5e2ab2481 to your computer and use it in GitHub Desktop.
Save willgarcia/371c9a30ebcf4d6d7a815da5e2ab2481 to your computer and use it in GitHub Desktop.
import boto3
import os
# Replace these with your AWS credentials or set them as environment variables
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY")
# Create AWS clients
ec2_client = boto3.client('ec2', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
elb_v2_client = boto3.client('elbv2', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
# Define the required MAP 2.0 tags
map_2_0_tags = {
'MAP2.0-Solution': 'ROSA',
'MAP2.0-AnalysisTimestamp': 'now',
}
def add_map_2_0_tags(resource_type, resource_id, resource_tags):
"""
Add the required MAP 2.0 tags to the specified resource.
"""
try:
if resource_type == 'instance':
ec2_client.create_tags(Resources=[resource_id], Tags=[{'Key': k, 'Value': v} for k, v in map_2_0_tags.items()])
elif resource_type == 'volume':
ec2_client.create_tags(Resources=[resource_id], Tags=[{'Key': k, 'Value': v} for k, v in map_2_0_tags.items()])
print(f"Added MAP 2.0 tags to {resource_type} {resource_id}")
except Exception as e:
print(f"Error adding MAP 2.0 tags to {resource_type} {resource_id}: {e}")
def detect_rosa_resources():
"""
Detect all EC2 instances, EBS volumes, and load balancers with the "red-hat-clustertype" tag set to "rosa",
and add the required MAP 2.0 tags to those resources.
"""
# Detect EC2 instances
instances = ec2_client.describe_instances(Filters=[{'Name': 'tag:red-hat-clustertype', 'Values': ['rosa']}])
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
instance_tags = {tag['Key']: tag['Value'] for tag in instance['Tags']}
print("Instance ID: {}".format(instance_id))
# add_map_2_0_tags('instance', instance_id, instance_tags)
# Detect EBS volumes
volumes = ec2_client.describe_volumes(Filters=[{'Name': 'tag:red-hat-clustertype', 'Values': ['rosa']}])
for volume in volumes['Volumes']:
volume_id = volume['VolumeId']
volume_tags = {tag['Key']: tag['Value'] for tag in volume['Tags']}
print("Volume ID: {}".format(volume_id))
# add_map_2_0_tags('volume', volume_id, volume_tags)
# Detect load balancers
find_rosa_elb_v2_load_balancers()
def add_map_2_0_tags_to_load_balancer(load_balancer_arn):
"""
Add the required MAP 2.0 tags to the specified load balancer.
"""
try:
elb_v2_client.add_tags(
ResourceArns=[load_balancer_arn],
Tags=[{'Key': k, 'Value': v} for k, v in map_2_0_tags.items()]
)
print(f"Added MAP 2.0 tags to load balancer {load_balancer_arn}")
except Exception as e:
print(f"Error adding MAP 2.0 tags to load balancer {load_balancer_arn}: {e}")
def find_rosa_elb_v2_load_balancers():
"""
Find all ELBv2 load balancers that have the "test=rosa" tag and add the required MAP 2.0 tags to them.
"""
try:
# Describe all load balancers
response = elb_v2_client.describe_load_balancers(
PageSize=100 # Adjust the page size as needed
)
load_balancers = response['LoadBalancers']
# Fetch all pages of results
while 'NextMarker' in response:
response = elb_v2_client.describe_load_balancers(
PageSize=100,
Marker=response['NextMarker']
)
load_balancers.extend(response['LoadBalancers'])
# Filter load balancers with "test=rosa" tag and add MAP 2.0 tags
for load_balancer in load_balancers:
load_balancer_arn = load_balancer['LoadBalancerArn']
load_balancer_tags = elb_v2_client.describe_tags(
ResourceArns=[load_balancer_arn]
)['TagDescriptions'][0]['Tags']
if any(tag['Key'] == 'red-hat-clustertype' and tag['Value'] == 'rosa' for tag in load_balancer_tags):
print("Load Balancer ARN: {}".format(load_balancer_arn))
# add_map_2_0_tags_to_load_balancer(load_balancer_arn)
except Exception as e:
print(f"Error finding ELBv2 load balancers with 'test=rosa' tag and adding MAP 2.0 tags: {e}")
if __name__ == "__main__":
detect_rosa_resources()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment