Untitled

mail@pastecode.io avatar
unknown
plain_text
23 days ago
1.9 kB
2
Indexable
Never
import boto3
import csv

def get_ssm_command_history(region, limit=100):
    # Initialize a boto3 SSM client with the specified region
    ssm_client = boto3.client('ssm', region_name=region)

    unique_ssm_docs = set()
    next_token = None

    while len(unique_ssm_docs) < limit:
        # Prepare the request parameters
        params = {
            'MaxResults': min(50, limit - len(unique_ssm_docs)),
            'Details': False
        }

        # Add the NextToken parameter if available
        if next_token:
            params['NextToken'] = next_token

        # Retrieve a batch of command invocations
        response = ssm_client.list_command_invocations(**params)

        # Add document names to the set
        unique_ssm_docs.update(invocation['DocumentName'] for invocation in response['CommandInvocations'])

        # Debugging: Print the current status
        print(f"Fetched {len(response['CommandInvocations'])} invocations, Total unique docs: {len(unique_ssm_docs)}")

        # Check if there are more results to fetch
        next_token = response.get('NextToken')
        if not next_token:
            break  # Exit if no more results are available

    return unique_ssm_docs

def save_to_csv(document_names, filename="ssm_documents.csv"):
    # Write the unique document names to a CSV file
    with open(filename, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['DocumentName'])  # Write header
        for doc_name in document_names:
            writer.writerow([doc_name])

if __name__ == "__main__":
    # Specify the region
    region = "us-east-1"  # Replace with your desired region

    # Query unique SSM document names
    unique_docs = get_ssm_command_history(region, 100)
    
    # Save to CSV file
    save_to_csv(unique_docs, "ssm_documents.csv")

    print(f"Unique SSM document names have been saved to 'ssm_documents.csv'.")
Leave a Comment