我想在下面向用户授予IAM权限。
权限:
BigQuery作业用户
浏览器
我知道如何通过Windows UI进行设置,但是我想通过python脚本设置此IAM权限吗?
答案 0 :(得分:0)
是的,可以通过使用Client Libraries来实现。
您可以在following documentation中查看一些示例。
我做了一个快速脚本,可以完成您所请求的操作:
from google.oauth2 import service_account
import googleapiclient.discovery
credentials = service_account.Credentials.from_service_account_file(
filename='PATH/TO/KEY.json',
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'cloudresourcemanager', 'v1', credentials=credentials)
def modify_policy_add_member(policy, role, member):
binding = next(b for b in policy['bindings'] if b['role'] == role)
binding['members'].append(member)
print(binding)
return policy
def create_role_add_member(policy, role, member):
"""Adds a new member to a role binding."""
binding = {
'role': role,
'members': [member]
}
print(binding)
policy['bindings'].append(binding)
return policy
if __name__ == "__main__":
project_id="YOUR_PROJECT_ID"
policy=service.projects().getIamPolicy(
resource=project_id,
body={},
).execute()
role="roles/bigquery.dataViewer" #example role to grant user
member="user:MEMBER_TO_ADD"
roles = [b['role'] for b in policy['bindings']]
if role in roles:
new_policy = modify_policy_add_member(policy, role, member)
else:
new_policy = create_role_add_member(policy, role, member)
print(new_policy)
policy = service.projects().setIamPolicy(
resource=project_id,
body={
'policy': new_policy,
}).execute()
按部分分解,脚本执行以下操作:
1-使用服务帐户密钥文件对API进行身份验证,范围为https://www.googleapis.com/auth/cloud-platform
。在此示例中,我使用了具有project/owner
权限的服务帐户密钥文件。
from google.oauth2 import service_account
import googleapiclient.discovery
credentials = service_account.Credentials.from_service_account_file(
filename='PATH/TO/KEY.json',
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'cloudresourcemanager', 'v1', credentials=credentials)
2-获取项目的当前政策:
policy=service.projects().getIamPolicy(
resource=project_id,
body={},
).execute()
3-设置要授予的角色,您可以在this list中看到该角色在BigQuery中。同样,设置成员以格式user:<USER_ADDRESS>
添加,您需要在添加帐户之前保留字符串user:
,除非要添加服务帐户,否则必须更改{{1 }}到user:
。
4-检查角色是否已经存在(如果存在),只需将成员追加到现有角色即可:
serviceaccount:
否则,创建角色并将其附加到策略绑定中:
def modify_policy_add_member(policy, role, member):
binding = next(b for b in policy['bindings'] if b['role'] == role)
binding['members'].append(member)
print(binding)
return policy
5-通过发送更新的策略来更新项目中的策略:
def create_role_add_member(policy, role, member):
"""Adds a new member to a role binding."""
binding = {
'role': role,
'members': [member]
}
print(binding)
policy['bindings'].append(binding)
return policy
请注意,要在Python中使用此API,您需要安装以下模块:
policy = service.projects().setIamPolicy(
resource=project_id,
body={
'policy': new_policy,
}).execute()