in cicd-deployers/dataform_runner.py [0:0]
def validate_service_account(project_id, service_account_email, required_role):
"""
Validates if a Google Cloud service account exists and has a specified role.
Args:
project_id: The ID of the Google Cloud project.
service_account_email: The email address of the service account.
required_role: The role the service account should have (e.g., "roles/storage.objectAdmin").
Returns:
True if the service account exists and has the role, False otherwise.
"""
# Construct the service account resource name
resource_name = f"//iam.googleapis.com/projects/{project_id}/serviceAccounts/{service_account_email}"
# Analyze IAM policy for the service account
response = iam_client.analyze_iam_policy(
request={
"analysis_query": {
"scope": f"projects/{project_id}",
"resource_selector": {"full_resource_name": resource_name},
"identity_selector": {"identity": f"serviceAccount:{service_account_email}"}
}
}
)
# Check if the required role is in the policy bindings
for binding in response.main_analysis.analysis_results[0].iam_binding.bindings:
if required_role in binding.role:
return True
return False
logging.info(f"Service account {service_account_email} does not have the role {required_role} in project {project_id}.")
return False