如何从Cloud Composer查询特定GCS Bucket的访问账号/服务账号及其权限类型
Answer
Great question! For GCS Buckets, the equivalent approach involves fetching the bucket's IAM policy, which works similarly to how you retrieve BigQuery dataset access controls but uses GCS's IAM system instead. Here's how you can implement this:
Prerequisites
- Ensure your Cloud Composer environment has the
google-cloud-storagelibrary available (it's typically pre-installed, but you can add it via PyPI if needed). - The Composer worker service account needs the
storage.buckets.getIamPolicypermission on the target GCS bucket.
Python Code Implementation
from google.cloud import storage def list_bucket_permissions(bucket_name): # Initialize the GCS client storage_client = storage.Client() # Fetch the target bucket object bucket = storage_client.get_bucket(bucket_name) # Retrieve the bucket's IAM policy (version 3 supports modern IAM features) iam_policy = bucket.get_iam_policy(requested_policy_version=3) # Iterate through each role-member binding in the policy for binding in iam_policy.bindings: role = binding["role"] members = binding["members"] print(f"*Role:* `{role}`") print("*Members with this role:*") for member in members: # Filter results to only service accounts (optional) if member.startswith("serviceAccount:"): print(f"- {member}") print("\n") # Example usage: Replace with your bucket name list_bucket_permissions("your-target-bucket-name")
Key Explanations
- IAM Policy Bindings: Unlike BigQuery's
access_entries, GCS uses IAM policy bindings that map predefined/custom roles (e.g.,roles/storage.objectAdmin) to a list of members (users, service accounts, groups, etc.). - Service Account Filtering: As shown in the code, you can narrow results to only service accounts by checking if the member string starts with
serviceAccount:. - Policy Version: Using
requested_policy_version=3ensures you can access condition-based permissions and other modern IAM features. For basic use cases, version 2 is also compatible.
Notes
- This code retrieves direct bucket-level permissions. If you need to account for inherited permissions from the project or organization level, you'll need to combine this with project-level IAM policy checks.
- In Cloud Composer, you can wrap this code in an Airflow PythonOperator to run it as part of your workflow.
内容的提问来源于stack exchange,提问作者Yugdhurandhar
相关产品推荐
相关产品推荐

