Created
April 29, 2024 07:27
-
-
Save made2591/c1c9b175abab60f7a547aaebc526267a to your computer and use it in GitHub Desktop.
List all ec2 that don't have tags defined
This file contains 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
import boto3 | |
import csv | |
def check_ec2_without_tag(tags_key_to_search, session): | |
# Initialize the EC2 client using the provided session | |
ec2_client = session.client('ec2') | |
# Define a dictionary to store instances without the given tag | |
instances_without_tag = [] | |
# Pagination loop to retrieve all instances | |
paginator = ec2_client.get_paginator('describe_instances') | |
for page in paginator.paginate(): | |
reservations = page['Reservations'] | |
for reservation in reservations: | |
for instance in reservation['Instances']: | |
instance_id = instance['InstanceId'] | |
tags = instance.get('Tags', []) | |
tag_keys = [tag['Key'] for tag in tags] | |
# Check if the tag key is not present in the instance's tags | |
for tag_key_to_search in tags_key_to_search: | |
if tag_key_to_search not in tag_keys: | |
instances_without_tag.append({'Profile': session.profile_name, 'InstanceID': instance_id, 'Missing': tag_key_to_search, 'Tags': tag_keys}) | |
return instances_without_tag | |
def write_to_csv(volumes): | |
# Define the CSV file name | |
csv_file = 'ec2_without_tags.csv' | |
# Write the volumes data to a CSV file | |
with open(csv_file, mode='w', newline='') as file: | |
fieldnames = ['Profile', 'InstanceID', 'Missing', 'Tags'] | |
writer = csv.DictWriter(file, fieldnames=fieldnames) | |
# Write header | |
writer.writeheader() | |
# Write each volume's details | |
for volume in volumes: | |
writer.writerow(volume) | |
print(f"Data written to {csv_file}") | |
def main(): | |
# Get the list of available profiles from the AWS config file | |
session = boto3.Session() | |
available_profiles = session.available_profiles | |
# Iterate over each profile | |
instances_without_tags = [] | |
for profile_name in available_profiles: | |
print(f"Processing profile: {profile_name}") | |
# Create a session using the current profile | |
session = boto3.Session(profile_name=profile_name) | |
tags_key_to_search = ["prima:domain","prima:environment"] | |
# Call the function to check EC2 instances without the tag | |
instances_without_tag = check_ec2_without_tag(tags_key_to_search, session) | |
# Add volumes of this profile to the list | |
instances_without_tags.extend(instances_without_tag) | |
# Write all unencrypted volumes to CSV | |
write_to_csv(instances_without_tags) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment