Skip to content

Instantly share code, notes, and snippets.

@yasmaryhd
Created February 26, 2025 20:04
Show Gist options
  • Save yasmaryhd/2be9e6d222a271169bf11eafea4f37fd to your computer and use it in GitHub Desktop.
Save yasmaryhd/2be9e6d222a271169bf11eafea4f37fd to your computer and use it in GitHub Desktop.
Pull iam role assigned for google group list
import os
import re
import csv
from collections import defaultdict
from datetime import datetime
"""
This script searches for roles assigned to specific Google groups in Terraform (.tf) files
and outputs a CSV file with the results.
To run the script:
1. Navigate to the directory where you want to run this from (e.g. terraform-config/workspaces).
2. Update the `google_groups` variable with list of google groups.
3. Use the following command to execute the script:
python3 _google-group-audit.py
The CSV file will be saved as terraform_google-group-audit_YYYY-MM-DD.csv where YYYY-MM-DD is the current date.
Output CSV columns:
- Google Group
- Role
- File
"""
# List of Google groups to search for
google_groups = [
"google-group-to-search-for"
]
group_patterns = [re.compile(f"group:{group}") for group in google_groups]
# Pattern to capture role assignments
ROLE_PATTERN = re.compile(r'role\s*=\s*"([^"]+)"')
# Structure to keep track of results
results = []
# Walk through the directory to find .tf files
for root, _, files in os.walk('.'):
for file in files:
if file.endswith('.tf'):
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
lines = f.readlines()
# Join the lines to a single string for easier regex operations
text = ''.join(lines)
# Find all occurrences of the group patterns and corresponding roles
for group_pattern in group_patterns:
if group_pattern.search(text):
# Get blocks containing both the group pattern and roles
blocks = re.split(r'}', text)
for block in blocks:
if group_pattern.search(block):
for match in re.finditer(ROLE_PATTERN, block):
role = match.group(1)
google_group = group_pattern.pattern.replace("group:", "")
results.append((google_group, role, file_path))
# Get today's date and format it as YYYY-MM-DD
today_date = datetime.today().strftime('%Y-%m-%d')
# Write results to CSV file with today's date in the filename
output_filename = f'terraform_google-group-audit_{today_date}.csv'
with open(output_filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Google Group', 'Role', 'File'])
for row in results:
writer.writerow(row)
print(f"Results written to {output_filename}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment