|
#!/usr/bin/env python |
|
|
|
# Copyright 2021 Google Inc. All Rights Reserved. |
|
# |
|
# Licensed under the Apache License, Version 2.0 (the "License"); |
|
# you may not use this file except in compliance with the License. |
|
# You may obtain a copy of the License at |
|
# |
|
# http://www.apache.org/licenses/LICENSE-2.0 |
|
# |
|
# Unless required by applicable law or agreed to in writing, software |
|
# distributed under the License is distributed on an "AS IS" BASIS, |
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
# See the License for the specific language governing permissions and |
|
# limitations under the License. |
|
|
|
import argparse |
|
import os |
|
import json |
|
from google.oauth2 import credentials |
|
import googleapiclient.discovery |
|
|
|
|
|
# [START iam_get_policy] |
|
def get_policy(project_id, version=1): |
|
"""Gets IAM policy for a project.""" |
|
creds = credentials.Credentials.from_authorized_user_file( |
|
filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"], |
|
scopes=["https://www.googleapis.com/auth/cloud-platform"], |
|
) |
|
service = googleapiclient.discovery.build( |
|
"cloudresourcemanager", "v1", credentials=creds |
|
) |
|
policy = ( |
|
service.projects() |
|
.getIamPolicy( |
|
resource=project_id, |
|
body={"options": {"requestedPolicyVersion": version}}, |
|
) |
|
.execute() |
|
) |
|
|
|
return policy |
|
# [END iam_get_policy] |
|
|
|
|
|
# [START main] |
|
def main(project_id, member_email): |
|
policy = get_policy(project_id) |
|
if member_email: |
|
result = { |
|
"member_email": member_email, |
|
"roles": [] |
|
} |
|
for binding in policy['bindings']: |
|
for member in binding['members']: |
|
if member.find(member_email) != -1: |
|
result['roles'].append(binding['role']) |
|
break |
|
else: |
|
result = policy |
|
|
|
print(json.dumps(result, indent=2)) |
|
# [END main] |
|
|
|
|
|
# [START run] |
|
if __name__ == '__main__': |
|
parser = argparse.ArgumentParser( |
|
description=__doc__, |
|
formatter_class=argparse.RawDescriptionHelpFormatter) |
|
parser.add_argument('-p', '--project', help='Your Google Cloud project ID.') |
|
parser.add_argument('-m', '--member_email', help='Member email to query for.') |
|
args = parser.parse_args() |
|
main(args.project, args.member_email) |
|
# [END run] |