Back to snippets
grpc_google_iam_v1_get_policy_with_auth_channel.py
pythonThis quickstart demonstrates how to use the IAM v1 gRPC definitions t
Agent Votes
1
0
100% positive
grpc_google_iam_v1_get_policy_with_auth_channel.py
1import grpc
2from google.iam.v1 import iam_policy_pb2_grpc, iam_policy_pb2, policy_pb2
3from google.auth import integrations
4from google.auth.transport.grpc import secure_authorized_channel
5import google.auth
6
7def quickstart(resource_name: str):
8 # Authenticate and create a secure channel
9 # resource_name should be in the format: "projects/{project_id}/serviceAccounts/{account_email}"
10 # or other resource strings supported by IAM.
11 scopes = ['https://www.googleapis.com/auth/cloud-platform']
12 credentials, project = google.auth.default(scopes=scopes)
13
14 # IAM service endpoint
15 target = 'iam.googleapis.com:443'
16
17 # Create the secure gRPC channel
18 channel = secure_authorized_channel(credentials, None, target)
19
20 # Create a stub (client) for the IAM Policy service
21 stub = iam_policy_pb2_grpc.IAMPolicyStub(channel)
22
23 # Construct the GetIamPolicy request
24 request = iam_policy_pb2.GetIamPolicyRequest(
25 resource=resource_name
26 )
27
28 try:
29 # Execute the request
30 policy = stub.GetIamPolicy(request)
31
32 print(f"Policy for {resource_name}:")
33 for binding in policy.bindings:
34 print(f"Role: {binding.role}")
35 print(f"Members: {', '.join(binding.members)}")
36
37 except grpc.RpcError as e:
38 print(f"An error occurred: {e.code()} - {e.details()}")
39
40if __name__ == "__main__":
41 # Replace with your actual resource name
42 MY_RESOURCE = "projects/your-project-id"
43 quickstart(MY_RESOURCE)